if (val === '') return true; if (val === 'false') return false; if (val === 'true') return true; return val; } if (DOCUMENT && typeof DOCUMENT.querySelector === 'function') { var attrs = [['data-family-prefix', 'familyPrefix'], ['data-replacement-class', 'replacementClass'], ['data-auto-replace-svg', 'autoReplaceSvg'], ['data-auto-add-css', 'autoAddCss'], ['data-auto-a11y', 'autoA11y'], ['data-search-pseudo-elements', 'searchPseudoElements'], ['data-observe-mutations', 'observeMutations'], ['data-mutate-approach', 'mutateApproach'], ['data-keep-original-source', 'keepOriginalSource'], ['data-measure-performance', 'measurePerformance'], ['data-show-missing-icons', 'showMissingIcons']]; attrs.forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), attr = _ref2[0], key = _ref2[1]; var val = coerce(getAttrConfig(attr)); if (val !== undefined && val !== null) { initial[key] = val; } }); } var _default = { familyPrefix: DEFAULT_FAMILY_PREFIX, replacementClass: DEFAULT_REPLACEMENT_CLASS, autoReplaceSvg: true, autoAddCss: true, autoA11y: true, searchPseudoElements: false, observeMutations: true, mutateApproach: 'async', keepOriginalSource: true, measurePerformance: false, showMissingIcons: true }; var _config = _objectSpread({}, _default, initial); if (!_config.autoReplaceSvg) _config.observeMutations = false; var config = _objectSpread({}, _config); WINDOW.FontAwesomeConfig = config; var w = WINDOW || {}; if (!w[NAMESPACE_IDENTIFIER]) w[NAMESPACE_IDENTIFIER] = {}; if (!w[NAMESPACE_IDENTIFIER].styles) w[NAMESPACE_IDENTIFIER].styles = {}; if (!w[NAMESPACE_IDENTIFIER].hooks) w[NAMESPACE_IDENTIFIER].hooks = {}; if (!w[NAMESPACE_IDENTIFIER].shims) w[NAMESPACE_IDENTIFIER].shims = []; var namespace = w[NAMESPACE_IDENTIFIER]; var functions = []; var listener = function listener() { DOCUMENT.removeEventListener('DOMContentLoaded', listener); loaded = 1; functions.map(function (fn) { return fn(); }); }; var loaded = false; if (IS_DOM) { loaded = (DOCUMENT.documentElement.doScroll ? /^loaded|^c/ : /^loaded|^i|^c/).test(DOCUMENT.readyState); if (!loaded) DOCUMENT.addEventListener('DOMContentLoaded', listener); } function domready (fn) { if (!IS_DOM) return; loaded ? setTimeout(fn, 0) : functions.push(fn); } var PENDING = 'pending'; var SETTLED = 'settled'; var FULFILLED = 'fulfilled'; var REJECTED = 'rejected'; var NOOP = function NOOP() {}; var isNode = typeof global !== 'undefined' && typeof global.process !== 'undefined' && typeof global.process.emit === 'function'; var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate; var asyncQueue = []; var asyncTimer; function asyncFlush() { // run promise callbacks for (var i = 0; i < asyncQueue.length; i++) { asyncQueue[i][0](asyncQueue[i][1]); } // reset async asyncQueue asyncQueue = []; asyncTimer = false; } function asyncCall(callback, arg) { asyncQueue.push([callback, arg]); if (!asyncTimer) { asyncTimer = true; asyncSetTimer(asyncFlush, 0); } } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch (e) { rejectPromise(e); } } function invokeCallback(subscriber) { var owner = subscriber.owner; var settled = owner._state; var value = owner._data; var callback = subscriber[settled]; var promise = subscriber.then; if (typeof callback === 'function') { settled = FULFILLED; try { value = callback(value); } catch (e) { reject(promise, e); } } if (!handleThenable(promise, value)) { if (settled === FULFILLED) { resolve(promise, value); } if (settled === REJECTED) { reject(promise, value); } } } function handleThenable(promise, value) { var resolved; try { if (promise === value) { throw new TypeError('A promises callback cannot return that same promise.'); } if (value && (typeof value === 'function' || _typeof(value) === 'object')) { // then should be retrieved only once var then = value.then; if (typeof then === 'function') { then.call(value, function (val) { if (!resolved) { resolved = true; if (value === val) { fulfill(promise, val); } else { resolve(promise, val); } } }, function (reason) { if (!resolved) { resolved = true; reject(promise, reason); } }); return true; } } } catch (e) { if (!resolved) { reject(promise, e); } return true; } return false; } function resolve(promise, value) { if (promise === value || !handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state === PENDING) { promise._state = SETTLED; promise._data = value; asyncCall(publishFulfillment, promise); } } function reject(promise, reason) { if (promise._state === PENDING) { promise._state = SETTLED; promise._data = reason; asyncCall(publishRejection, promise); } } function publish(promise) { promise._then = promise._then.forEach(invokeCallback); } function publishFulfillment(promise) { promise._state = FULFILLED; publish(promise); } function publishRejection(promise) { promise._state = REJECTED; publish(promise); if (!promise._handled && isNode) { global.process.emit('unhandledRejection', promise._data, promise); } } function notifyRejectionHandled(promise) { global.process.emit('rejectionHandled', promise); } /** * @class */ function P(resolver) { if (typeof resolver !== 'function') { throw new TypeError('Promise resolver ' + resolver + ' is not a function'); } if (this instanceof P === false) { throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); } this._then = []; invokeResolver(resolver, this); } P.prototype = { constructor: P, _state: PENDING, _then: null, _data: undefined, _handled: false, then: function then(onFulfillment, onRejection) { var subscriber = { owner: this, then: new this.constructor(NOOP), fulfilled: onFulfillment, rejected: onRejection }; if ((onRejection || onFulfillment) && !this._handled) { this._handled = true; if (this._state === REJECTED && isNode) { asyncCall(notifyRejectionHandled, this); } } if (this._state === FULFILLED || this._state === REJECTED) { // already resolved, call callback async asyncCall(invokeCallback, subscriber); } else { // subscribe this._then.push(subscriber); } return subscriber.then; }, catch: function _catch(onRejection) { return this.then(null, onRejection); } }; P.all = function (promises) { if (!Array.isArray(promises)) { throw new TypeError('You must pass an array to Promise.all().'); } return new P(function (resolve, reject) { var results = []; var remaining = 0; function resolver(index) { remaining++; return function (value) { results[index] = value; if (! --remaining) { resolve(results); } }; } for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolver(i), reject); } else { results[i] = promise; } } if (!remaining) { resolve(results); } }); }; P.race = function (promises) { if (!Array.isArray(promises)) { throw new TypeError('You must pass an array to Promise.race().'); } return new P(function (resolve, reject) { for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); }; P.resolve = function (value) { if (value && _typeof(value) === 'object' && value.constructor === P) { return value; } return new P(function (resolve) { resolve(value); }); }; P.reject = function (reason) { return new P(function (resolve, reject) { reject(reason); }); }; var picked = typeof Promise === 'function' ? Promise : P; var d = UNITS_IN_GRID; var meaninglessTransform = { size: 16, x: 0, y: 0, rotate: 0, flipX: false, flipY: false }; function isReserved(name) { return ~RESERVED_CLASSES.indexOf(name); } function bunker(fn) { try { fn(); } catch (e) { if (!PRODUCTION) { throw e; } } } function insertCss(css) { if (!css || !IS_DOM) { return; } var style = DOCUMENT.createElement('style'); style.setAttribute('type', 'text/css'); style.innerHTML = css; var headChildren = DOCUMENT.head.childNodes; var beforeChild = null; for (var i = headChildren.length - 1; i > -1; i--) { var child = headChildren[i]; var tagName = (child.tagName || '').toUpperCase(); if (['STYLE', 'LINK'].indexOf(tagName) > -1) { beforeChild = child; } } DOCUMENT.head.insertBefore(style, beforeChild); return css; } var idPool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; function nextUniqueId() { var size = 12; var id = ''; while (size-- > 0) { id += idPool[Math.random() * 62 | 0]; } return id; } function toArray(obj) { var array = []; for (var i = (obj || []).length >>> 0; i--;) { array[i] = obj[i]; } return array; } function classArray(node) { if (node.classList) { return toArray(node.classList); } else { return (node.getAttribute('class') || '').split(' ').filter(function (i) { return i; }); } } function getIconName(familyPrefix, cls) { var parts = cls.split('-'); var prefix = parts[0]; var iconName = parts.slice(1).join('-'); if (prefix === familyPrefix && iconName !== '' && !isReserved(iconName)) { return iconName; } else { return null; } } function htmlEscape(str) { return "".concat(str).replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>'); } function joinAttributes(attributes) { return Object.keys(attributes || {}).reduce(function (acc, attributeName) { return acc + "".concat(attributeName, "=\"").concat(htmlEscape(attributes[attributeName]), "\" "); }, '').trim(); } function joinStyles(styles) { return Object.keys(styles || {}).reduce(function (acc, styleName) { return acc + "".concat(styleName, ": ").concat(styles[styleName], ";"); }, ''); } function transformIsMeaningful(transform) { return transform.size !== meaninglessTransform.size || transform.x !== meaninglessTransform.x || transform.y !== meaninglessTransform.y || transform.rotate !== meaninglessTransform.rotate || transform.flipX || transform.flipY; } function transformForSvg(_ref) { var transform = _ref.transform, containerWidth = _ref.containerWidth, iconWidth = _ref.iconWidth; var outer = { transform: "translate(".concat(containerWidth / 2, " 256)") }; var innerTranslate = "translate(".concat(transform.x * 32, ", ").concat(transform.y * 32, ") "); var innerScale = "scale(".concat(transform.size / 16 * (transform.flipX ? -1 : 1), ", ").concat(transform.size / 16 * (transform.flipY ? -1 : 1), ") "); var innerRotate = "rotate(".concat(transform.rotate, " 0 0)"); var inner = { transform: "".concat(innerTranslate, " ").concat(innerScale, " ").concat(innerRotate) }; var path = { transform: "translate(".concat(iconWidth / 2 * -1, " -256)") }; return { outer: outer, inner: inner, path: path }; } function transformForCss(_ref2) { var transform = _ref2.transform, _ref2$width = _ref2.width, width = _ref2$width === void 0 ? UNITS_IN_GRID : _ref2$width, _ref2$height = _ref2.height, height = _ref2$height === void 0 ? UNITS_IN_GRID : _ref2$height, _ref2$startCentered = _ref2.startCentered, startCentered = _ref2$startCentered === void 0 ? false : _ref2$startCentered; var val = ''; if (startCentered && IS_IE) { val += "translate(".concat(transform.x / d - width / 2, "em, ").concat(transform.y / d - height / 2, "em) "); } else if (startCentered) { val += "translate(calc(-50% + ".concat(transform.x / d, "em), calc(-50% + ").concat(transform.y / d, "em)) "); } else { val += "translate(".concat(transform.x / d, "em, ").concat(transform.y / d, "em) "); } val += "scale(".concat(transform.size / d * (transform.flipX ? -1 : 1), ", ").concat(transform.size / d * (transform.flipY ? -1 : 1), ") "); val += "rotate(".concat(transform.rotate, "deg) "); return val; } var ALL_SPACE = { x: 0, y: 0, width: '100%', height: '100%' }; function fillBlack(abstract) { var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; if (abstract.attributes && (abstract.attributes.fill || force)) { abstract.attributes.fill = 'black'; } return abstract; } function deGroup(abstract) { if (abstract.tag === 'g') { return abstract.children; } else { return [abstract]; } } function makeIconMasking (_ref) { var children = _ref.children, attributes = _ref.attributes, main = _ref.main, mask = _ref.mask, explicitMaskId = _ref.maskId, transform = _ref.transform; var mainWidth = main.width, mainPath = main.icon; var maskWidth = mask.width, maskPath = mask.icon; var trans = transformForSvg({ transform: transform, containerWidth: maskWidth, iconWidth: mainWidth }); var maskRect = { tag: 'rect', attributes: _objectSpread({}, ALL_SPACE, { fill: 'white' }) }; var maskInnerGroupChildrenMixin = mainPath.children ? { children: mainPath.children.map(fillBlack) } : {}; var maskInnerGroup = { tag: 'g', attributes: _objectSpread({}, trans.inner), children: [fillBlack(_objectSpread({ tag: mainPath.tag, attributes: _objectSpread({}, mainPath.attributes, trans.path) }, maskInnerGroupChildrenMixin))] }; var maskOuterGroup = { tag: 'g', attributes: _objectSpread({}, trans.outer), children: [maskInnerGroup] }; var maskId = "mask-".concat(explicitMaskId || nextUniqueId()); var clipId = "clip-".concat(explicitMaskId || nextUniqueId()); var maskTag = { tag: 'mask', attributes: _objectSpread({}, ALL_SPACE, { id: maskId, maskUnits: 'userSpaceOnUse', maskContentUnits: 'userSpaceOnUse' }), children: [maskRect, maskOuterGroup] }; var defs = { tag: 'defs', children: [{ tag: 'clipPath', attributes: { id: clipId }, children: deGroup(maskPath) }, maskTag] }; children.push(defs, { tag: 'rect', attributes: _objectSpread({ fill: 'currentColor', 'clip-path': "url(#".concat(clipId, ")"), mask: "url(#".concat(maskId, ")") }, ALL_SPACE) }); return { children: children, attributes: attributes }; } function makeIconStandard (_ref) { var children = _ref.children, attributes = _ref.attributes, main = _ref.main, transform = _ref.transform, styles = _ref.styles; var styleString = joinStyles(styles); if (styleString.length > 0) { attributes['style'] = styleString; } if (transformIsMeaningful(transform)) { var trans = transformForSvg({ transform: transform, containerWidth: main.width, iconWidth: main.width }); children.push({ tag: 'g', attributes: _objectSpread({}, trans.outer), children: [{ tag: 'g', attributes: _objectSpread({}, trans.inner), children: [{ tag: main.icon.tag, children: main.icon.children, attributes: _objectSpread({}, main.icon.attributes, trans.path) }] }] }); } else { children.push(main.icon); } return { children: children, attributes: attributes }; } function asIcon (_ref) { var children = _ref.children, main = _ref.main, mask = _ref.mask, attributes = _ref.attributes, styles = _ref.styles, transform = _ref.transform; if (transformIsMeaningful(transform) && main.found && !mask.found) { var width = main.width, height = main.height; var offset = { x: width / height / 2, y: 0.5 }; attributes['style'] = joinStyles(_objectSpread({}, styles, { 'transform-origin': "".concat(offset.x + transform.x / 16, "em ").concat(offset.y + transform.y / 16, "em") })); } return [{ tag: 'svg', attributes: attributes, children: children }]; } function asSymbol (_ref) { var prefix = _ref.prefix, iconName = _ref.iconName, children = _ref.children, attributes = _ref.attributes, symbol = _ref.symbol; var id = symbol === true ? "".concat(prefix, "-").concat(config.familyPrefix, "-").concat(iconName) : symbol; return [{ tag: 'svg', attributes: { style: 'display: none;' }, children: [{ tag: 'symbol', attributes: _objectSpread({}, attributes, { id: id }), children: children }] }]; } function makeInlineSvgAbstract(params) { var _params$icons = params.icons, main = _params$icons.main, mask = _params$icons.mask, prefix = params.prefix, iconName = params.iconName, transform = params.transform, symbol = params.symbol, title = params.title, maskId = params.maskId, titleId = params.titleId, extra = params.extra, _params$watchable = params.watchable, watchable = _params$watchable === void 0 ? false : _params$watchable; var _ref = mask.found ? mask : main, width = _ref.width, height = _ref.height; var widthClass = "fa-w-".concat(Math.ceil(width / height * 16)); var attrClass = [config.replacementClass, iconName ? "".concat(config.familyPrefix, "-").concat(iconName) : '', widthClass].filter(function (c) { return extra.classes.indexOf(c) === -1; }).concat(extra.classes).join(' '); var content = { children: [], attributes: _objectSpread({}, extra.attributes, { 'data-prefix': prefix, 'data-icon': iconName, 'class': attrClass, 'role': extra.attributes.role || 'img', 'xmlns': 'http://www.w3.org/2000/svg', 'viewBox': "0 0 ".concat(width, " ").concat(height) }) }; if (watchable) { content.attributes[DATA_FA_I2SVG] = ''; } if (title) content.children.push({ tag: 'title', attributes: { id: content.attributes['aria-labelledby'] || "title-".concat(titleId || nextUniqueId()) }, children: [title] }); var args = _objectSpread({}, content, { prefix: prefix, iconName: iconName, main: main, mask: mask, maskId: maskId, transform: transform, symbol: symbol, styles: extra.styles }); var _ref2 = mask.found && main.found ? makeIconMasking(args) : makeIconStandard(args), children = _ref2.children, attributes = _ref2.attributes; args.children = children; args.attributes = attributes; if (symbol) { return asSymbol(args); } else { return asIcon(args); } } function makeLayersTextAbstract(params) { var content = params.content, width = params.width, height = params.height, transform = params.transform, title = params.title, extra = params.extra, _params$watchable2 = params.watchable, watchable = _params$watchable2 === void 0 ? false : _params$watchable2; var attributes = _objectSpread({}, extra.attributes, title ? { 'title': title } : {}, { 'class': extra.classes.join(' ') }); if (watchable) { attributes[DATA_FA_I2SVG] = ''; } var styles = _objectSpread({}, extra.styles); if (transformIsMeaningful(transform)) { styles['transform'] = transformForCss({ transform: transform, startCentered: true, width: width, height: height }); styles['-webkit-transform'] = styles['transform']; } var styleString = joinStyles(styles); if (styleString.length > 0) { attributes['style'] = styleString; } var val = []; val.push({ tag: 'span', attributes: attributes, children: [content] }); if (title) { val.push({ tag: 'span', attributes: { class: 'sr-only' }, children: [title] }); } return val; } function makeLayersCounterAbstract(params) { var content = params.content, title = params.title, extra = params.extra; var attributes = _objectSpread({}, extra.attributes, title ? { 'title': title } : {}, { 'class': extra.classes.join(' ') }); var styleString = joinStyles(extra.styles); if (styleString.length > 0) { attributes['style'] = styleString; } var val = []; val.push({ tag: 'span', attributes: attributes, children: [content] }); if (title) { val.push({ tag: 'span', attributes: { class: 'sr-only' }, children: [title] }); } return val; } var noop$1 = function noop() {}; var p = config.measurePerformance && PERFORMANCE && PERFORMANCE.mark && PERFORMANCE.measure ? PERFORMANCE : { mark: noop$1, measure: noop$1 }; var preamble = "FA \"5.13.1\""; var begin = function begin(name) { p.mark("".concat(preamble, " ").concat(name, " begins")); return function () { return end(name); }; }; var end = function end(name) { p.mark("".concat(preamble, " ").concat(name, " ends")); p.measure("".concat(preamble, " ").concat(name), "".concat(preamble, " ").concat(name, " begins"), "".concat(preamble, " ").concat(name, " ends")); }; var perf = { begin: begin, end: end }; /** * Internal helper to bind a function known to have 4 arguments * to a given context. */ var bindInternal4 = function bindInternal4(func, thisContext) { return function (a, b, c, d) { return func.call(thisContext, a, b, c, d); }; }; /** * # Reduce * * A fast object `.reduce()` implementation. * * @param {Object} subject The object to reduce over. * @param {Function} fn The reducer function. * @param {mixed} initialValue The initial value for the reducer, defaults to subject[0]. * @param {Object} thisContext The context for the reducer. * @return {mixed} The final result. */ var reduce = function fastReduceObject(subject, fn, initialValue, thisContext) { var keys = Object.keys(subject), length = keys.length, iterator = thisContext !== undefined ? bindInternal4(fn, thisContext) : fn, i, key, result; if (initialValue === undefined) { i = 1; result = subject[keys[0]]; } else { i = 0; result = initialValue; } for (; i < length; i++) { key = keys[i]; result = iterator(result, subject[key], key, subject); } return result; }; function toHex(unicode) { var result = ''; for (var i = 0; i < unicode.length; i++) { var hex = unicode.charCodeAt(i).toString(16); result += ('000' + hex).slice(-4); } return result; } function defineIcons(prefix, icons) { var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var _params$skipHooks = params.skipHooks, skipHooks = _params$skipHooks === void 0 ? false : _params$skipHooks; var normalized = Object.keys(icons).reduce(function (acc, iconName) { var icon = icons[iconName]; var expanded = !!icon.icon; if (expanded) { acc[icon.iconName] = icon.icon; } else { acc[iconName] = icon; } return acc; }, {}); if (typeof namespace.hooks.addPack === 'function' && !skipHooks) { namespace.hooks.addPack(prefix, normalized); } else { namespace.styles[prefix] = _objectSpread({}, namespace.styles[prefix] || {}, normalized); } /** * Font Awesome 4 used the prefix of `fa` for all icons. With the introduction * of new styles we needed to differentiate between them. Prefix `fa` is now an alias * for `fas` so we'll easy the upgrade process for our users by automatically defining * this as well. */ if (prefix === 'fas') { defineIcons('fa', icons); } } var styles = namespace.styles, shims = namespace.shims; var _byUnicode = {}; var _byLigature = {}; var _byOldName = {}; var build = function build() { var lookup = function lookup(reducer) { return reduce(styles, function (o, style, prefix) { o[prefix] = reduce(style, reducer, {}); return o; }, {}); }; _byUnicode = lookup(function (acc, icon, iconName) { if (icon[3]) { acc[icon[3]] = iconName; } return acc; }); _byLigature = lookup(function (acc, icon, iconName) { var ligatures = icon[2]; acc[iconName] = iconName; ligatures.forEach(function (ligature) { acc[ligature] = iconName; }); return acc; }); var hasRegular = 'far' in styles; _byOldName = reduce(shims, function (acc, shim) { var oldName = shim[0]; var prefix = shim[1]; var iconName = shim[2]; if (prefix === 'far' && !hasRegular) { prefix = 'fas'; } acc[oldName] = { prefix: prefix, iconName: iconName }; return acc; }, {}); }; build(); function byUnicode(prefix, unicode) { return (_byUnicode[prefix] || {})[unicode]; } function byLigature(prefix, ligature) { return (_byLigature[prefix] || {})[ligature]; } function byOldName(name) { return _byOldName[name] || { prefix: null, iconName: null }; } var styles$1 = namespace.styles; var emptyCanonicalIcon = function emptyCanonicalIcon() { return { prefix: null, iconName: null, rest: [] }; }; function getCanonicalIcon(values) { return values.reduce(function (acc, cls) { var iconName = getIconName(config.familyPrefix, cls); if (styles$1[cls]) { acc.prefix = cls; } else if (config.autoFetchSvg && ['fas', 'far', 'fal', 'fad', 'fab', 'fa'].indexOf(cls) > -1) { acc.prefix = cls; } else if (iconName) { var shim = acc.prefix === 'fa' ? byOldName(iconName) : {}; acc.iconName = shim.iconName || iconName; acc.prefix = shim.prefix || acc.prefix; } else if (cls !== config.replacementClass && cls.indexOf('fa-w-') !== 0) { acc.rest.push(cls); } return acc; }, emptyCanonicalIcon()); } function iconFromMapping(mapping, prefix, iconName) { if (mapping && mapping[prefix] && mapping[prefix][iconName]) { return { prefix: prefix, iconName: iconName, icon: mapping[prefix][iconName] }; } } function toHtml(abstractNodes) { var tag = abstractNodes.tag, _abstractNodes$attrib = abstractNodes.attributes, attributes = _abstractNodes$attrib === void 0 ? {} : _abstractNodes$attrib, _abstractNodes$childr = abstractNodes.children, children = _abstractNodes$childr === void 0 ? [] : _abstractNodes$childr; if (typeof abstractNodes === 'string') { return htmlEscape(abstractNodes); } else { return "<".concat(tag, " ").concat(joinAttributes(attributes), ">").concat(children.map(toHtml).join(''), ""); } } var noop$2 = function noop() {}; function isWatched(node) { var i2svg = node.getAttribute ? node.getAttribute(DATA_FA_I2SVG) : null; return typeof i2svg === 'string'; } function getMutator() { if (config.autoReplaceSvg === true) { return mutators.replace; } var mutator = mutators[config.autoReplaceSvg]; return mutator || mutators.replace; } var mutators = { replace: function replace(mutation) { var node = mutation[0]; var abstract = mutation[1]; var newOuterHTML = abstract.map(function (a) { return toHtml(a); }).join('\n'); if (node.parentNode && node.outerHTML) { node.outerHTML = newOuterHTML + (config.keepOriginalSource && node.tagName.toLowerCase() !== 'svg' ? "") : ''); } else if (node.parentNode) { var newNode = document.createElement('span'); node.parentNode.replaceChild(newNode, node); newNode.outerHTML = newOuterHTML; } }, nest: function nest(mutation) { var node = mutation[0]; var abstract = mutation[1]; // If we already have a replaced node we do not want to continue nesting within it. // Short-circuit to the standard replacement if (~classArray(node).indexOf(config.replacementClass)) { return mutators.replace(mutation); } var forSvg = new RegExp("".concat(config.familyPrefix, "-.*")); delete abstract[0].attributes.style; delete abstract[0].attributes.id; var splitClasses = abstract[0].attributes.class.split(' ').reduce(function (acc, cls) { if (cls === config.replacementClass || cls.match(forSvg)) { acc.toSvg.push(cls); } else { acc.toNode.push(cls); } return acc; }, { toNode: [], toSvg: [] }); abstract[0].attributes.class = splitClasses.toSvg.join(' '); var newInnerHTML = abstract.map(function (a) { return toHtml(a); }).join('\n'); node.setAttribute('class', splitClasses.toNode.join(' ')); node.setAttribute(DATA_FA_I2SVG, ''); node.innerHTML = newInnerHTML; } }; function performOperationSync(op) { op(); } function perform(mutations, callback) { var callbackFunction = typeof callback === 'function' ? callback : noop$2; if (mutations.length === 0) { callbackFunction(); } else { var frame = performOperationSync; if (config.mutateApproach === MUTATION_APPROACH_ASYNC) { frame = WINDOW.requestAnimationFrame || performOperationSync; } frame(function () { var mutator = getMutator(); var mark = perf.begin('mutate'); mutations.map(mutator); mark(); callbackFunction(); }); } } var disabled = false; function disableObservation() { disabled = true; } function enableObservation() { disabled = false; } var mo = null; function observe(options) { if (!MUTATION_OBSERVER) { return; } if (!config.observeMutations) { return; } var treeCallback = options.treeCallback, nodeCallback = options.nodeCallback, pseudoElementsCallback = options.pseudoElementsCallback, _options$observeMutat = options.observeMutationsRoot, observeMutationsRoot = _options$observeMutat === void 0 ? DOCUMENT : _options$observeMutat; mo = new MUTATION_OBSERVER(function (objects) { if (disabled) return; toArray(objects).forEach(function (mutationRecord) { if (mutationRecord.type === 'childList' && mutationRecord.addedNodes.length > 0 && !isWatched(mutationRecord.addedNodes[0])) { if (config.searchPseudoElements) { pseudoElementsCallback(mutationRecord.target); } treeCallback(mutationRecord.target); } if (mutationRecord.type === 'attributes' && mutationRecord.target.parentNode && config.searchPseudoElements) { pseudoElementsCallback(mutationRecord.target.parentNode); } if (mutationRecord.type === 'attributes' && isWatched(mutationRecord.target) && ~ATTRIBUTES_WATCHED_FOR_MUTATION.indexOf(mutationRecord.attributeName)) { if (mutationRecord.attributeName === 'class') { var _getCanonicalIcon = getCanonicalIcon(classArray(mutationRecord.target)), prefix = _getCanonicalIcon.prefix, iconName = _getCanonicalIcon.iconName; if (prefix) mutationRecord.target.setAttribute('data-prefix', prefix); if (iconName) mutationRecord.target.setAttribute('data-icon', iconName); } else { nodeCallback(mutationRecord.target); } } }); }); if (!IS_DOM) return; mo.observe(observeMutationsRoot, { childList: true, attributes: true, characterData: true, subtree: true }); } function disconnect() { if (!mo) return; mo.disconnect(); } function styleParser (node) { var style = node.getAttribute('style'); var val = []; if (style) { val = style.split(';').reduce(function (acc, style) { var styles = style.split(':'); var prop = styles[0]; var value = styles.slice(1); if (prop && value.length > 0) { acc[prop] = value.join(':').trim(); } return acc; }, {}); } return val; } function classParser (node) { var existingPrefix = node.getAttribute('data-prefix'); var existingIconName = node.getAttribute('data-icon'); var innerText = node.innerText !== undefined ? node.innerText.trim() : ''; var val = getCanonicalIcon(classArray(node)); if (existingPrefix && existingIconName) { val.prefix = existingPrefix; val.iconName = existingIconName; } if (val.prefix && innerText.length > 1) { val.iconName = byLigature(val.prefix, node.innerText); } else if (val.prefix && innerText.length === 1) { val.iconName = byUnicode(val.prefix, toHex(node.innerText)); } return val; } var parseTransformString = function parseTransformString(transformString) { var transform = { size: 16, x: 0, y: 0, flipX: false, flipY: false, rotate: 0 }; if (!transformString) { return transform; } else { return transformString.toLowerCase().split(' ').reduce(function (acc, n) { var parts = n.toLowerCase().split('-'); var first = parts[0]; var rest = parts.slice(1).join('-'); if (first && rest === 'h') { acc.flipX = true; return acc; } if (first && rest === 'v') { acc.flipY = true; return acc; } rest = parseFloat(rest); if (isNaN(rest)) { return acc; } switch (first) { case 'grow': acc.size = acc.size + rest; break; case 'shrink': acc.size = acc.size - rest; break; case 'left': acc.x = acc.x - rest; break; case 'right': acc.x = acc.x + rest; break; case 'up': acc.y = acc.y - rest; break; case 'down': acc.y = acc.y + rest; break; case 'rotate': acc.rotate = acc.rotate + rest; break; } return acc; }, transform); } }; function transformParser (node) { return parseTransformString(node.getAttribute('data-fa-transform')); } function symbolParser (node) { var symbol = node.getAttribute('data-fa-symbol'); return symbol === null ? false : symbol === '' ? true : symbol; } function attributesParser (node) { var extraAttributes = toArray(node.attributes).reduce(function (acc, attr) { if (acc.name !== 'class' && acc.name !== 'style') { acc[attr.name] = attr.value; } return acc; }, {}); var title = node.getAttribute('title'); var titleId = node.getAttribute('data-fa-title-id'); if (config.autoA11y) { if (title) { extraAttributes['aria-labelledby'] = "".concat(config.replacementClass, "-title-").concat(titleId || nextUniqueId()); } else { extraAttributes['aria-hidden'] = 'true'; extraAttributes['focusable'] = 'false'; } } return extraAttributes; } function maskParser (node) { var mask = node.getAttribute('data-fa-mask'); if (!mask) { return emptyCanonicalIcon(); } else { return getCanonicalIcon(mask.split(' ').map(function (i) { return i.trim(); })); } } function blankMeta() { return { iconName: null, title: null, titleId: null, prefix: null, transform: meaninglessTransform, symbol: false, mask: null, maskId: null, extra: { classes: [], styles: {}, attributes: {} } }; } function parseMeta(node) { var _classParser = classParser(node), iconName = _classParser.iconName, prefix = _classParser.prefix, extraClasses = _classParser.rest; var extraStyles = styleParser(node); var transform = transformParser(node); var symbol = symbolParser(node); var extraAttributes = attributesParser(node); var mask = maskParser(node); return { iconName: iconName, title: node.getAttribute('title'), titleId: node.getAttribute('data-fa-title-id'), prefix: prefix, transform: transform, symbol: symbol, mask: mask, maskId: node.getAttribute('data-fa-mask-id'), extra: { classes: extraClasses, styles: extraStyles, attributes: extraAttributes } }; } function MissingIcon(error) { this.name = 'MissingIcon'; this.message = error || 'Icon unavailable'; this.stack = new Error().stack; } MissingIcon.prototype = Object.create(Error.prototype); MissingIcon.prototype.constructor = MissingIcon; var FILL = { fill: 'currentColor' }; var ANIMATION_BASE = { attributeType: 'XML', repeatCount: 'indefinite', dur: '2s' }; var RING = { tag: 'path', attributes: _objectSpread({}, FILL, { d: 'M156.5,447.7l-12.6,29.5c-18.7-9.5-35.9-21.2-51.5-34.9l22.7-22.7C127.6,430.5,141.5,440,156.5,447.7z M40.6,272H8.5 c1.4,21.2,5.4,41.7,11.7,61.1L50,321.2C45.1,305.5,41.8,289,40.6,272z M40.6,240c1.4-18.8,5.2-37,11.1-54.1l-29.5-12.6 C14.7,194.3,10,216.7,8.5,240H40.6z M64.3,156.5c7.8-14.9,17.2-28.8,28.1-41.5L69.7,92.3c-13.7,15.6-25.5,32.8-34.9,51.5 L64.3,156.5z M397,419.6c-13.9,12-29.4,22.3-46.1,30.4l11.9,29.8c20.7-9.9,39.8-22.6,56.9-37.6L397,419.6z M115,92.4 c13.9-12,29.4-22.3,46.1-30.4l-11.9-29.8c-20.7,9.9-39.8,22.6-56.8,37.6L115,92.4z M447.7,355.5c-7.8,14.9-17.2,28.8-28.1,41.5 l22.7,22.7c13.7-15.6,25.5-32.9,34.9-51.5L447.7,355.5z M471.4,272c-1.4,18.8-5.2,37-11.1,54.1l29.5,12.6 c7.5-21.1,12.2-43.5,13.6-66.8H471.4z M321.2,462c-15.7,5-32.2,8.2-49.2,9.4v32.1c21.2-1.4,41.7-5.4,61.1-11.7L321.2,462z M240,471.4c-18.8-1.4-37-5.2-54.1-11.1l-12.6,29.5c21.1,7.5,43.5,12.2,66.8,13.6V471.4z M462,190.8c5,15.7,8.2,32.2,9.4,49.2h32.1 c-1.4-21.2-5.4-41.7-11.7-61.1L462,190.8z M92.4,397c-12-13.9-22.3-29.4-30.4-46.1l-29.8,11.9c9.9,20.7,22.6,39.8,37.6,56.9 L92.4,397z M272,40.6c18.8,1.4,36.9,5.2,54.1,11.1l12.6-29.5C317.7,14.7,295.3,10,272,8.5V40.6z M190.8,50 c15.7-5,32.2-8.2,49.2-9.4V8.5c-21.2,1.4-41.7,5.4-61.1,11.7L190.8,50z M442.3,92.3L419.6,115c12,13.9,22.3,29.4,30.5,46.1 l29.8-11.9C470,128.5,457.3,109.4,442.3,92.3z M397,92.4l22.7-22.7c-15.6-13.7-32.8-25.5-51.5-34.9l-12.6,29.5 C370.4,72.1,384.4,81.5,397,92.4z' }) }; var OPACITY_ANIMATE = _objectSpread({}, ANIMATION_BASE, { attributeName: 'opacity' }); var DOT = { tag: 'circle', attributes: _objectSpread({}, FILL, { cx: '256', cy: '364', r: '28' }), children: [{ tag: 'animate', attributes: _objectSpread({}, ANIMATION_BASE, { attributeName: 'r', values: '28;14;28;28;14;28;' }) }, { tag: 'animate', attributes: _objectSpread({}, OPACITY_ANIMATE, { values: '1;0;1;1;0;1;' }) }] }; var QUESTION = { tag: 'path', attributes: _objectSpread({}, FILL, { opacity: '1', d: 'M263.7,312h-16c-6.6,0-12-5.4-12-12c0-71,77.4-63.9,77.4-107.8c0-20-17.8-40.2-57.4-40.2c-29.1,0-44.3,9.6-59.2,28.7 c-3.9,5-11.1,6-16.2,2.4l-13.1-9.2c-5.6-3.9-6.9-11.8-2.6-17.2c21.2-27.2,46.4-44.7,91.2-44.7c52.3,0,97.4,29.8,97.4,80.2 c0,67.6-77.4,63.5-77.4,107.8C275.7,306.6,270.3,312,263.7,312z' }), children: [{ tag: 'animate', attributes: _objectSpread({}, OPACITY_ANIMATE, { values: '1;0;0;0;0;1;' }) }] }; var EXCLAMATION = { tag: 'path', attributes: _objectSpread({}, FILL, { opacity: '0', d: 'M232.5,134.5l7,168c0.3,6.4,5.6,11.5,12,11.5h9c6.4,0,11.7-5.1,12-11.5l7-168c0.3-6.8-5.2-12.5-12-12.5h-23 C237.7,122,232.2,127.7,232.5,134.5z' }), children: [{ tag: 'animate', attributes: _objectSpread({}, OPACITY_ANIMATE, { values: '0;0;1;1;0;0;' }) }] }; var missing = { tag: 'g', children: [RING, DOT, QUESTION, EXCLAMATION] }; var styles$2 = namespace.styles; function asFoundIcon(icon) { var width = icon[0]; var height = icon[1]; var _icon$slice = icon.slice(4), _icon$slice2 = _slicedToArray(_icon$slice, 1), vectorData = _icon$slice2[0]; var element = null; if (Array.isArray(vectorData)) { element = { tag: 'g', attributes: { class: "".concat(config.familyPrefix, "-").concat(DUOTONE_CLASSES.GROUP) }, children: [{ tag: 'path', attributes: { class: "".concat(config.familyPrefix, "-").concat(DUOTONE_CLASSES.SECONDARY), fill: 'currentColor', d: vectorData[0] } }, { tag: 'path', attributes: { class: "".concat(config.familyPrefix, "-").concat(DUOTONE_CLASSES.PRIMARY), fill: 'currentColor', d: vectorData[1] } }] }; } else { element = { tag: 'path', attributes: { fill: 'currentColor', d: vectorData } }; } return { found: true, width: width, height: height, icon: element }; } function findIcon(iconName, prefix) { return new picked(function (resolve, reject) { var val = { found: false, width: 512, height: 512, icon: missing }; if (iconName && prefix && styles$2[prefix] && styles$2[prefix][iconName]) { var icon = styles$2[prefix][iconName]; return resolve(asFoundIcon(icon)); } var headers = {}; if (_typeof(WINDOW.FontAwesomeKitConfig) === 'object' && typeof window.FontAwesomeKitConfig.token === 'string') { headers['fa-kit-token'] = WINDOW.FontAwesomeKitConfig.token; } if (iconName && prefix && !config.showMissingIcons) { reject(new MissingIcon("Icon is missing for prefix ".concat(prefix, " with icon name ").concat(iconName))); } else { resolve(val); } }); } var styles$3 = namespace.styles; function generateSvgReplacementMutation(node, nodeMeta) { var iconName = nodeMeta.iconName, title = nodeMeta.title, titleId = nodeMeta.titleId, prefix = nodeMeta.prefix, transform = nodeMeta.transform, symbol = nodeMeta.symbol, mask = nodeMeta.mask, maskId = nodeMeta.maskId, extra = nodeMeta.extra; return new picked(function (resolve, reject) { picked.all([findIcon(iconName, prefix), findIcon(mask.iconName, mask.prefix)]).then(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), main = _ref2[0], mask = _ref2[1]; resolve([node, makeInlineSvgAbstract({ icons: { main: main, mask: mask }, prefix: prefix, iconName: iconName, transform: transform, symbol: symbol, mask: mask, maskId: maskId, title: title, titleId: titleId, extra: extra, watchable: true })]); }); }); } function generateLayersText(node, nodeMeta) { var title = nodeMeta.title, transform = nodeMeta.transform, extra = nodeMeta.extra; var width = null; var height = null; if (IS_IE) { var computedFontSize = parseInt(getComputedStyle(node).fontSize, 10); var boundingClientRect = node.getBoundingClientRect(); width = boundingClientRect.width / computedFontSize; height = boundingClientRect.height / computedFontSize; } if (config.autoA11y && !title) { extra.attributes['aria-hidden'] = 'true'; } return picked.resolve([node, makeLayersTextAbstract({ content: node.innerHTML, width: width, height: height, transform: transform, title: title, extra: extra, watchable: true })]); } function generateMutation(node) { var nodeMeta = parseMeta(node); if (~nodeMeta.extra.classes.indexOf(LAYERS_TEXT_CLASSNAME)) { return generateLayersText(node, nodeMeta); } else { return generateSvgReplacementMutation(node, nodeMeta); } } function onTree(root) { var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (!IS_DOM) return; var htmlClassList = DOCUMENT.documentElement.classList; var hclAdd = function hclAdd(suffix) { return htmlClassList.add("".concat(HTML_CLASS_I2SVG_BASE_CLASS, "-").concat(suffix)); }; var hclRemove = function hclRemove(suffix) { return htmlClassList.remove("".concat(HTML_CLASS_I2SVG_BASE_CLASS, "-").concat(suffix)); }; var prefixes = config.autoFetchSvg ? Object.keys(PREFIX_TO_STYLE) : Object.keys(styles$3); var prefixesDomQuery = [".".concat(LAYERS_TEXT_CLASSNAME, ":not([").concat(DATA_FA_I2SVG, "])")].concat(prefixes.map(function (p) { return ".".concat(p, ":not([").concat(DATA_FA_I2SVG, "])"); })).join(', '); if (prefixesDomQuery.length === 0) { return; } var candidates = []; try { candidates = toArray(root.querySelectorAll(prefixesDomQuery)); } catch (e) {// noop } if (candidates.length > 0) { hclAdd('pending'); hclRemove('complete'); } else { return; } var mark = perf.begin('onTree'); var mutations = candidates.reduce(function (acc, node) { try { var mutation = generateMutation(node); if (mutation) { acc.push(mutation); } } catch (e) { if (!PRODUCTION) { if (e instanceof MissingIcon) { console.error(e); } } } return acc; }, []); return new picked(function (resolve, reject) { picked.all(mutations).then(function (resolvedMutations) { perform(resolvedMutations, function () { hclAdd('active'); hclAdd('complete'); hclRemove('pending'); if (typeof callback === 'function') callback(); mark(); resolve(); }); }).catch(function () { mark(); reject(); }); }); } function onNode(node) { var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; generateMutation(node).then(function (mutation) { if (mutation) { perform([mutation], callback); } }); } function replaceForPosition(node, position) { var pendingAttribute = "".concat(DATA_FA_PSEUDO_ELEMENT_PENDING).concat(position.replace(':', '-')); return new picked(function (resolve, reject) { if (node.getAttribute(pendingAttribute) !== null) { // This node is already being processed return resolve(); } var children = toArray(node.children); var alreadyProcessedPseudoElement = children.filter(function (c) { return c.getAttribute(DATA_FA_PSEUDO_ELEMENT) === position; })[0]; var styles = WINDOW.getComputedStyle(node, position); var fontFamily = styles.getPropertyValue('font-family').match(FONT_FAMILY_PATTERN); var fontWeight = styles.getPropertyValue('font-weight'); var content = styles.getPropertyValue('content'); if (alreadyProcessedPseudoElement && !fontFamily) { // If we've already processed it but the current computed style does not result in a font-family, // that probably means that a class name that was previously present to make the icon has been // removed. So we now should delete the icon. node.removeChild(alreadyProcessedPseudoElement); return resolve(); } else if (fontFamily && content !== 'none' && content !== '') { var prefix = ~['Solid', 'Regular', 'Light', 'Duotone', 'Brands'].indexOf(fontFamily[1]) ? STYLE_TO_PREFIX[fontFamily[1].toLowerCase()] : FONT_WEIGHT_TO_PREFIX[fontWeight]; var hexValue = toHex(content.length === 3 ? content.substr(1, 1) : content); var iconName = byUnicode(prefix, hexValue); var iconIdentifier = iconName; // Only convert the pseudo element in this :before/:after position into an icon if we haven't // already done so with the same prefix and iconName if (iconName && (!alreadyProcessedPseudoElement || alreadyProcessedPseudoElement.getAttribute(DATA_PREFIX) !== prefix || alreadyProcessedPseudoElement.getAttribute(DATA_ICON) !== iconIdentifier)) { node.setAttribute(pendingAttribute, iconIdentifier); if (alreadyProcessedPseudoElement) { // Delete the old one, since we're replacing it with a new one node.removeChild(alreadyProcessedPseudoElement); } var meta = blankMeta(); var extra = meta.extra; extra.attributes[DATA_FA_PSEUDO_ELEMENT] = position; findIcon(iconName, prefix).then(function (main) { var abstract = makeInlineSvgAbstract(_objectSpread({}, meta, { icons: { main: main, mask: emptyCanonicalIcon() }, prefix: prefix, iconName: iconIdentifier, extra: extra, watchable: true })); var element = DOCUMENT.createElement('svg'); if (position === ':before') { node.insertBefore(element, node.firstChild); } else { node.appendChild(element); } element.outerHTML = abstract.map(function (a) { return toHtml(a); }).join('\n'); node.removeAttribute(pendingAttribute); resolve(); }).catch(reject); } else { resolve(); } } else { resolve(); } }); } function replace(node) { return picked.all([replaceForPosition(node, ':before'), replaceForPosition(node, ':after')]); } function processable(node) { return node.parentNode !== document.head && !~TAGNAMES_TO_SKIP_FOR_PSEUDOELEMENTS.indexOf(node.tagName.toUpperCase()) && !node.getAttribute(DATA_FA_PSEUDO_ELEMENT) && (!node.parentNode || node.parentNode.tagName !== 'svg'); } function searchPseudoElements (root) { if (!IS_DOM) return; return new picked(function (resolve, reject) { var operations = toArray(root.querySelectorAll('*')).filter(processable).map(replace); var end = perf.begin('searchPseudoElements'); disableObservation(); picked.all(operations).then(function () { end(); enableObservation(); resolve(); }).catch(function () { end(); enableObservation(); reject(); }); }); } var baseStyles = "svg:not(:root).svg-inline--fa{overflow:visible}.svg-inline--fa{display:inline-block;font-size:inherit;height:1em;overflow:visible;vertical-align:-.125em}.svg-inline--fa.fa-lg{vertical-align:-.225em}.svg-inline--fa.fa-w-1{width:.0625em}.svg-inline--fa.fa-w-2{width:.125em}.svg-inline--fa.fa-w-3{width:.1875em}.svg-inline--fa.fa-w-4{width:.25em}.svg-inline--fa.fa-w-5{width:.3125em}.svg-inline--fa.fa-w-6{width:.375em}.svg-inline--fa.fa-w-7{width:.4375em}.svg-inline--fa.fa-w-8{width:.5em}.svg-inline--fa.fa-w-9{width:.5625em}.svg-inline--fa.fa-w-10{width:.625em}.svg-inline--fa.fa-w-11{width:.6875em}.svg-inline--fa.fa-w-12{width:.75em}.svg-inline--fa.fa-w-13{width:.8125em}.svg-inline--fa.fa-w-14{width:.875em}.svg-inline--fa.fa-w-15{width:.9375em}.svg-inline--fa.fa-w-16{width:1em}.svg-inline--fa.fa-w-17{width:1.0625em}.svg-inline--fa.fa-w-18{width:1.125em}.svg-inline--fa.fa-w-19{width:1.1875em}.svg-inline--fa.fa-w-20{width:1.25em}.svg-inline--fa.fa-pull-left{margin-right:.3em;width:auto}.svg-inline--fa.fa-pull-right{margin-left:.3em;width:auto}.svg-inline--fa.fa-border{height:1.5em}.svg-inline--fa.fa-li{width:2em}.svg-inline--fa.fa-fw{width:1.25em}.fa-layers svg.svg-inline--fa{bottom:0;left:0;margin:auto;position:absolute;right:0;top:0}.fa-layers{display:inline-block;height:1em;position:relative;text-align:center;vertical-align:-.125em;width:1em}.fa-layers svg.svg-inline--fa{-webkit-transform-origin:center center;transform-origin:center center}.fa-layers-counter,.fa-layers-text{display:inline-block;position:absolute;text-align:center}.fa-layers-text{left:50%;top:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);-webkit-transform-origin:center center;transform-origin:center center}.fa-layers-counter{background-color:#ff253a;border-radius:1em;-webkit-box-sizing:border-box;box-sizing:border-box;color:#fff;height:1.5em;line-height:1;max-width:5em;min-width:1.5em;overflow:hidden;padding:.25em;right:0;text-overflow:ellipsis;top:0;-webkit-transform:scale(.25);transform:scale(.25);-webkit-transform-origin:top right;transform-origin:top right}.fa-layers-bottom-right{bottom:0;right:0;top:auto;-webkit-transform:scale(.25);transform:scale(.25);-webkit-transform-origin:bottom right;transform-origin:bottom right}.fa-layers-bottom-left{bottom:0;left:0;right:auto;top:auto;-webkit-transform:scale(.25);transform:scale(.25);-webkit-transform-origin:bottom left;transform-origin:bottom left}.fa-layers-top-right{right:0;top:0;-webkit-transform:scale(.25);transform:scale(.25);-webkit-transform-origin:top right;transform-origin:top right}.fa-layers-top-left{left:0;right:auto;top:0;-webkit-transform:scale(.25);transform:scale(.25);-webkit-transform-origin:top left;transform-origin:top left}.fa-lg{font-size:1.3333333333em;line-height:.75em;vertical-align:-.0667em}.fa-xs{font-size:.75em}.fa-sm{font-size:.875em}.fa-1x{font-size:1em}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-6x{font-size:6em}.fa-7x{font-size:7em}.fa-8x{font-size:8em}.fa-9x{font-size:9em}.fa-10x{font-size:10em}.fa-fw{text-align:center;width:1.25em}.fa-ul{list-style-type:none;margin-left:2.5em;padding-left:0}.fa-ul>li{position:relative}.fa-li{left:-2em;position:absolute;text-align:center;width:2em;line-height:inherit}.fa-border{border:solid .08em #eee;border-radius:.1em;padding:.2em .25em .15em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left,.fab.fa-pull-left,.fal.fa-pull-left,.far.fa-pull-left,.fas.fa-pull-left{margin-right:.3em}.fa.fa-pull-right,.fab.fa-pull-right,.fal.fa-pull-right,.far.fa-pull-right,.fas.fa-pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.fa-rotate-90{-webkit-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-webkit-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-webkit-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-webkit-transform:scale(-1,1);transform:scale(-1,1)}.fa-flip-vertical{-webkit-transform:scale(1,-1);transform:scale(1,-1)}.fa-flip-both,.fa-flip-horizontal.fa-flip-vertical{-webkit-transform:scale(-1,-1);transform:scale(-1,-1)}:root .fa-flip-both,:root .fa-flip-horizontal,:root .fa-flip-vertical,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-rotate-90{-webkit-filter:none;filter:none}.fa-stack{display:inline-block;height:2em;position:relative;width:2.5em}.fa-stack-1x,.fa-stack-2x{bottom:0;left:0;margin:auto;position:absolute;right:0;top:0}.svg-inline--fa.fa-stack-1x{height:1em;width:1.25em}.svg-inline--fa.fa-stack-2x{height:2em;width:2.5em}.fa-inverse{color:#fff}.sr-only{border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.sr-only-focusable:active,.sr-only-focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}.svg-inline--fa .fa-primary{fill:var(--fa-primary-color,currentColor);opacity:1;opacity:var(--fa-primary-opacity,1)}.svg-inline--fa .fa-secondary{fill:var(--fa-secondary-color,currentColor);opacity:.4;opacity:var(--fa-secondary-opacity,.4)}.svg-inline--fa.fa-swap-opacity .fa-primary{opacity:.4;opacity:var(--fa-secondary-opacity,.4)}.svg-inline--fa.fa-swap-opacity .fa-secondary{opacity:1;opacity:var(--fa-primary-opacity,1)}.svg-inline--fa mask .fa-primary,.svg-inline--fa mask .fa-secondary{fill:#000}.fad.fa-inverse{color:#fff}"; function css () { var dfp = DEFAULT_FAMILY_PREFIX; var drc = DEFAULT_REPLACEMENT_CLASS; var fp = config.familyPrefix; var rc = config.replacementClass; var s = baseStyles; if (fp !== dfp || rc !== drc) { var dPatt = new RegExp("\\.".concat(dfp, "\\-"), 'g'); var customPropPatt = new RegExp("\\--".concat(dfp, "\\-"), 'g'); var rPatt = new RegExp("\\.".concat(drc), 'g'); s = s.replace(dPatt, ".".concat(fp, "-")).replace(customPropPatt, "--".concat(fp, "-")).replace(rPatt, ".".concat(rc)); } return s; } var Library = /*#__PURE__*/ function () { function Library() { _classCallCheck(this, Library); this.definitions = {}; } _createClass(Library, [{ key: "add", value: function add() { var _this = this; for (var _len = arguments.length, definitions = new Array(_len), _key = 0; _key < _len; _key++) { definitions[_key] = arguments[_key]; } var additions = definitions.reduce(this._pullDefinitions, {}); Object.keys(additions).forEach(function (key) { _this.definitions[key] = _objectSpread({}, _this.definitions[key] || {}, additions[key]); defineIcons(key, additions[key]); build(); }); } }, { key: "reset", value: function reset() { this.definitions = {}; } }, { key: "_pullDefinitions", value: function _pullDefinitions(additions, definition) { var normalized = definition.prefix && definition.iconName && definition.icon ? { 0: definition } : definition; Object.keys(normalized).map(function (key) { var _normalized$key = normalized[key], prefix = _normalized$key.prefix, iconName = _normalized$key.iconName, icon = _normalized$key.icon; if (!additions[prefix]) additions[prefix] = {}; additions[prefix][iconName] = icon; }); return additions; } }]); return Library; }(); function ensureCss() { if (config.autoAddCss && !_cssInserted) { insertCss(css()); _cssInserted = true; } } function apiObject(val, abstractCreator) { Object.defineProperty(val, 'abstract', { get: abstractCreator }); Object.defineProperty(val, 'html', { get: function get() { return val.abstract.map(function (a) { return toHtml(a); }); } }); Object.defineProperty(val, 'node', { get: function get() { if (!IS_DOM) return; var container = DOCUMENT.createElement('div'); container.innerHTML = val.html; return container.children; } }); return val; } function findIconDefinition(iconLookup) { var _iconLookup$prefix = iconLookup.prefix, prefix = _iconLookup$prefix === void 0 ? 'fa' : _iconLookup$prefix, iconName = iconLookup.iconName; if (!iconName) return; return iconFromMapping(library.definitions, prefix, iconName) || iconFromMapping(namespace.styles, prefix, iconName); } function resolveIcons(next) { return function (maybeIconDefinition) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var iconDefinition = (maybeIconDefinition || {}).icon ? maybeIconDefinition : findIconDefinition(maybeIconDefinition || {}); var mask = params.mask; if (mask) { mask = (mask || {}).icon ? mask : findIconDefinition(mask || {}); } return next(iconDefinition, _objectSpread({}, params, { mask: mask })); }; } var library = new Library(); var noAuto = function noAuto() { config.autoReplaceSvg = false; config.observeMutations = false; disconnect(); }; var _cssInserted = false; var dom = { i2svg: function i2svg() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (IS_DOM) { ensureCss(); var _params$node = params.node, node = _params$node === void 0 ? DOCUMENT : _params$node, _params$callback = params.callback, callback = _params$callback === void 0 ? function () {} : _params$callback; if (config.searchPseudoElements) { searchPseudoElements(node); } return onTree(node, callback); } else { return picked.reject('Operation requires a DOM of some kind.'); } }, css: css, insertCss: function insertCss$$1() { if (!_cssInserted) { insertCss(css()); _cssInserted = true; } }, watch: function watch() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var autoReplaceSvgRoot = params.autoReplaceSvgRoot, observeMutationsRoot = params.observeMutationsRoot; if (config.autoReplaceSvg === false) { config.autoReplaceSvg = true; } config.observeMutations = true; domready(function () { autoReplace({ autoReplaceSvgRoot: autoReplaceSvgRoot }); observe({ treeCallback: onTree, nodeCallback: onNode, pseudoElementsCallback: searchPseudoElements, observeMutationsRoot: observeMutationsRoot }); }); } }; var parse = { transform: function transform(transformString) { return parseTransformString(transformString); } }; var icon = resolveIcons(function (iconDefinition) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _params$transform = params.transform, transform = _params$transform === void 0 ? meaninglessTransform : _params$transform, _params$symbol = params.symbol, symbol = _params$symbol === void 0 ? false : _params$symbol, _params$mask = params.mask, mask = _params$mask === void 0 ? null : _params$mask, _params$maskId = params.maskId, maskId = _params$maskId === void 0 ? null : _params$maskId, _params$title = params.title, title = _params$title === void 0 ? null : _params$title, _params$titleId = params.titleId, titleId = _params$titleId === void 0 ? null : _params$titleId, _params$classes = params.classes, classes = _params$classes === void 0 ? [] : _params$classes, _params$attributes = params.attributes, attributes = _params$attributes === void 0 ? {} : _params$attributes, _params$styles = params.styles, styles = _params$styles === void 0 ? {} : _params$styles; if (!iconDefinition) return; var prefix = iconDefinition.prefix, iconName = iconDefinition.iconName, icon = iconDefinition.icon; return apiObject(_objectSpread({ type: 'icon' }, iconDefinition), function () { ensureCss(); if (config.autoA11y) { if (title) { attributes['aria-labelledby'] = "".concat(config.replacementClass, "-title-").concat(titleId || nextUniqueId()); } else { attributes['aria-hidden'] = 'true'; attributes['focusable'] = 'false'; } } return makeInlineSvgAbstract({ icons: { main: asFoundIcon(icon), mask: mask ? asFoundIcon(mask.icon) : { found: false, width: null, height: null, icon: {} } }, prefix: prefix, iconName: iconName, transform: _objectSpread({}, meaninglessTransform, transform), symbol: symbol, title: title, maskId: maskId, titleId: titleId, extra: { attributes: attributes, styles: styles, classes: classes } }); }); }); var text = function text(content) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _params$transform2 = params.transform, transform = _params$transform2 === void 0 ? meaninglessTransform : _params$transform2, _params$title2 = params.title, title = _params$title2 === void 0 ? null : _params$title2, _params$classes2 = params.classes, classes = _params$classes2 === void 0 ? [] : _params$classes2, _params$attributes2 = params.attributes, attributes = _params$attributes2 === void 0 ? {} : _params$attributes2, _params$styles2 = params.styles, styles = _params$styles2 === void 0 ? {} : _params$styles2; return apiObject({ type: 'text', content: content }, function () { ensureCss(); return makeLayersTextAbstract({ content: content, transform: _objectSpread({}, meaninglessTransform, transform), title: title, extra: { attributes: attributes, styles: styles, classes: ["".concat(config.familyPrefix, "-layers-text")].concat(_toConsumableArray(classes)) } }); }); }; var counter = function counter(content) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _params$title3 = params.title, title = _params$title3 === void 0 ? null : _params$title3, _params$classes3 = params.classes, classes = _params$classes3 === void 0 ? [] : _params$classes3, _params$attributes3 = params.attributes, attributes = _params$attributes3 === void 0 ? {} : _params$attributes3, _params$styles3 = params.styles, styles = _params$styles3 === void 0 ? {} : _params$styles3; return apiObject({ type: 'counter', content: content }, function () { ensureCss(); return makeLayersCounterAbstract({ content: content.toString(), title: title, extra: { attributes: attributes, styles: styles, classes: ["".concat(config.familyPrefix, "-layers-counter")].concat(_toConsumableArray(classes)) } }); }); }; var layer = function layer(assembler) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _params$classes4 = params.classes, classes = _params$classes4 === void 0 ? [] : _params$classes4; return apiObject({ type: 'layer' }, function () { ensureCss(); var children = []; assembler(function (args) { Array.isArray(args) ? args.map(function (a) { children = children.concat(a.abstract); }) : children = children.concat(args.abstract); }); return [{ tag: 'span', attributes: { class: ["".concat(config.familyPrefix, "-layers")].concat(_toConsumableArray(classes)).join(' ') }, children: children }]; }); }; var api = { noAuto: noAuto, config: config, dom: dom, library: library, parse: parse, findIconDefinition: findIconDefinition, icon: icon, text: text, counter: counter, layer: layer, toHtml: toHtml }; var autoReplace = function autoReplace() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _params$autoReplaceSv = params.autoReplaceSvgRoot, autoReplaceSvgRoot = _params$autoReplaceSv === void 0 ? DOCUMENT : _params$autoReplaceSv; if ((Object.keys(namespace.styles).length > 0 || config.autoFetchSvg) && IS_DOM && config.autoReplaceSvg) api.dom.i2svg({ node: autoReplaceSvgRoot }); }; function bootstrap() { if (IS_BROWSER) { if (!WINDOW.FontAwesome) { WINDOW.FontAwesome = api; } domready(function () { autoReplace(); observe({ treeCallback: onTree, nodeCallback: onNode, pseudoElementsCallback: searchPseudoElements }); }); } namespace.hooks = _objectSpread({}, namespace.hooks, { addPack: function addPack(prefix, icons) { namespace.styles[prefix] = _objectSpread({}, namespace.styles[prefix] || {}, icons); build(); autoReplace(); }, addShims: function addShims(shims) { var _namespace$shims; (_namespace$shims = namespace.shims).push.apply(_namespace$shims, _toConsumableArray(shims)); build(); autoReplace(); } }); } bunker(bootstrap); }()); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) },{"timers":393}],4:[function(require,module,exports){ /*! * @pixi/accessibility - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/accessibility is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var utils = require('@pixi/utils'); var display = require('@pixi/display'); /** * Default property values of accessible objects * used by {@link PIXI.accessibility.AccessibilityManager}. * * @private * @function accessibleTarget * @memberof PIXI.accessibility * @type {Object} * @example * function MyObject() {} * * Object.assign( * MyObject.prototype, * PIXI.accessibility.accessibleTarget * ); */ var accessibleTarget = { /** * Flag for if the object is accessible. If true AccessibilityManager will overlay a * shadow div with attributes set * * @member {boolean} * @memberof PIXI.DisplayObject# */ accessible: false, /** * Sets the title attribute of the shadow div * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' * * @member {?string} * @memberof PIXI.DisplayObject# */ accessibleTitle: null, /** * Sets the aria-label attribute of the shadow div * * @member {string} * @memberof PIXI.DisplayObject# */ accessibleHint: null, /** * @member {number} * @memberof PIXI.DisplayObject# * @private * @todo Needs docs. */ tabIndex: 0, /** * @member {boolean} * @memberof PIXI.DisplayObject# * @todo Needs docs. */ _accessibleActive: false, /** * @member {boolean} * @memberof PIXI.DisplayObject# * @todo Needs docs. */ _accessibleDiv: false, /** * Specify the type of div the accessible layer is. Screen readers treat the element differently * depending on this type. Defaults to button. * * @member {string} * @memberof PIXI.DisplayObject# * @default 'button' */ accessibleType: 'button', /** * Specify the pointer-events the accessible div will use * Defaults to auto. * * @member {string} * @memberof PIXI.DisplayObject# * @default 'auto' */ accessiblePointerEvents: 'auto', /** * Setting to false will prevent any children inside this container to * be accessible. Defaults to true. * * @member {boolean} * @memberof PIXI.DisplayObject# * @default true */ accessibleChildren: true, }; // add some extra variables to the container.. display.DisplayObject.mixin(accessibleTarget); var KEY_CODE_TAB = 9; var DIV_TOUCH_SIZE = 100; var DIV_TOUCH_POS_X = 0; var DIV_TOUCH_POS_Y = 0; var DIV_TOUCH_ZINDEX = 2; var DIV_HOOK_SIZE = 1; var DIV_HOOK_POS_X = -1000; var DIV_HOOK_POS_Y = -1000; var DIV_HOOK_ZINDEX = 2; /** * The Accessibility manager recreates the ability to tab and have content read by screen readers. * This is very important as it can possibly help people with disabilities access PixiJS content. * * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the * events as if the mouse was being used, minimizing the effort required to implement. * * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility` * * @class * @memberof PIXI.accessibility */ var AccessibilityManager = function AccessibilityManager(renderer) { /** * @type {?HTMLElement} * @private */ this._hookDiv = null; if (utils.isMobile.tablet || utils.isMobile.phone) { this.createTouchHook(); } // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. var div = document.createElement('div'); div.style.width = DIV_TOUCH_SIZE + "px"; div.style.height = DIV_TOUCH_SIZE + "px"; div.style.position = 'absolute'; div.style.top = DIV_TOUCH_POS_X + "px"; div.style.left = DIV_TOUCH_POS_Y + "px"; div.style.zIndex = DIV_TOUCH_ZINDEX; /** * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. * * @type {HTMLElement} * @private */ this.div = div; /** * A simple pool for storing divs. * * @type {*} * @private */ this.pool = []; /** * This is a tick used to check if an object is no longer being rendered. * * @type {Number} * @private */ this.renderId = 0; /** * Setting this to true will visually show the divs. * * @type {boolean} */ this.debug = false; /** * The renderer this accessibility manager works for. * * @member {PIXI.AbstractRenderer} */ this.renderer = renderer; /** * The array of currently active accessible items. * * @member {Array<*>} * @private */ this.children = []; /** * pre-bind the functions * * @type {Function} * @private */ this._onKeyDown = this._onKeyDown.bind(this); /** * pre-bind the functions * * @type {Function} * @private */ this._onMouseMove = this._onMouseMove.bind(this); /** * A flag * @type {boolean} * @readonly */ this.isActive = false; /** * A flag * @type {boolean} * @readonly */ this.isMobileAccessibility = false; // let listen for tab.. once pressed we can fire up and show the accessibility layer window.addEventListener('keydown', this._onKeyDown, false); }; /** * Creates the touch hooks. * * @private */ AccessibilityManager.prototype.createTouchHook = function createTouchHook () { var this$1 = this; var hookDiv = document.createElement('button'); hookDiv.style.width = DIV_HOOK_SIZE + "px"; hookDiv.style.height = DIV_HOOK_SIZE + "px"; hookDiv.style.position = 'absolute'; hookDiv.style.top = DIV_HOOK_POS_X + "px"; hookDiv.style.left = DIV_HOOK_POS_Y + "px"; hookDiv.style.zIndex = DIV_HOOK_ZINDEX; hookDiv.style.backgroundColor = '#FF0000'; hookDiv.title = 'HOOK DIV'; hookDiv.addEventListener('focus', function () { this$1.isMobileAccessibility = true; this$1.activate(); this$1.destroyTouchHook(); }); document.body.appendChild(hookDiv); this._hookDiv = hookDiv; }; /** * Destroys the touch hooks. * * @private */ AccessibilityManager.prototype.destroyTouchHook = function destroyTouchHook () { if (!this._hookDiv) { return; } document.body.removeChild(this._hookDiv); this._hookDiv = null; }; /** * Activating will cause the Accessibility layer to be shown. * This is called when a user presses the tab key. * * @private */ AccessibilityManager.prototype.activate = function activate () { if (this.isActive) { return; } this.isActive = true; window.document.addEventListener('mousemove', this._onMouseMove, true); window.removeEventListener('keydown', this._onKeyDown, false); this.renderer.on('postrender', this.update, this); if (this.renderer.view.parentNode) { this.renderer.view.parentNode.appendChild(this.div); } }; /** * Deactivating will cause the Accessibility layer to be hidden. * This is called when a user moves the mouse. * * @private */ AccessibilityManager.prototype.deactivate = function deactivate () { if (!this.isActive || this.isMobileAccessibility) { return; } this.isActive = false; window.document.removeEventListener('mousemove', this._onMouseMove, true); window.addEventListener('keydown', this._onKeyDown, false); this.renderer.off('postrender', this.update); if (this.div.parentNode) { this.div.parentNode.removeChild(this.div); } }; /** * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. * * @private * @param {PIXI.Container} displayObject - The DisplayObject to check. */ AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects (displayObject) { if (!displayObject.visible || !displayObject.accessibleChildren) { return; } if (displayObject.accessible && displayObject.interactive) { if (!displayObject._accessibleActive) { this.addChild(displayObject); } displayObject.renderId = this.renderId; } var children = displayObject.children; for (var i = 0; i < children.length; i++) { this.updateAccessibleObjects(children[i]); } }; /** * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. * * @private */ AccessibilityManager.prototype.update = function update () { if (!this.renderer.renderingToScreen) { return; } // update children... this.updateAccessibleObjects(this.renderer._lastObjectRendered); var rect = this.renderer.view.getBoundingClientRect(); var sx = rect.width / this.renderer.width; var sy = rect.height / this.renderer.height; var div = this.div; div.style.left = (rect.left) + "px"; div.style.top = (rect.top) + "px"; div.style.width = (this.renderer.width) + "px"; div.style.height = (this.renderer.height) + "px"; for (var i = 0; i < this.children.length; i++) { var child = this.children[i]; if (child.renderId !== this.renderId) { child._accessibleActive = false; utils.removeItems(this.children, i, 1); this.div.removeChild(child._accessibleDiv); this.pool.push(child._accessibleDiv); child._accessibleDiv = null; i--; if (this.children.length === 0) { this.deactivate(); } } else { // map div to display.. div = child._accessibleDiv; var hitArea = child.hitArea; var wt = child.worldTransform; if (child.hitArea) { div.style.left = ((wt.tx + (hitArea.x * wt.a)) * sx) + "px"; div.style.top = ((wt.ty + (hitArea.y * wt.d)) * sy) + "px"; div.style.width = (hitArea.width * wt.a * sx) + "px"; div.style.height = (hitArea.height * wt.d * sy) + "px"; } else { hitArea = child.getBounds(); this.capHitArea(hitArea); div.style.left = (hitArea.x * sx) + "px"; div.style.top = (hitArea.y * sy) + "px"; div.style.width = (hitArea.width * sx) + "px"; div.style.height = (hitArea.height * sy) + "px"; // update button titles and hints if they exist and they've changed if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { div.title = child.accessibleTitle; } if (div.getAttribute('aria-label') !== child.accessibleHint && child.accessibleHint !== null) { div.setAttribute('aria-label', child.accessibleHint); } } // the title or index may have changed, if so lets update it! if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) { div.title = child.accessibleTitle; div.tabIndex = child.tabIndex; if (this.debug) { this.updateDebugHTML(div); } } } } // increment the render id.. this.renderId++; }; /** * private function that will visually add the information to the * accessability div * * @param {HTMLDivElement} div */ AccessibilityManager.prototype.updateDebugHTML = function updateDebugHTML (div) { div.innerHTML = "type: " + (div.type) + "
title : " + (div.title) + "
tabIndex: " + (div.tabIndex); }; /** * Adjust the hit area based on the bounds of a display object * * @param {PIXI.Rectangle} hitArea - Bounds of the child */ AccessibilityManager.prototype.capHitArea = function capHitArea (hitArea) { if (hitArea.x < 0) { hitArea.width += hitArea.x; hitArea.x = 0; } if (hitArea.y < 0) { hitArea.height += hitArea.y; hitArea.y = 0; } if (hitArea.x + hitArea.width > this.renderer.width) { hitArea.width = this.renderer.width - hitArea.x; } if (hitArea.y + hitArea.height > this.renderer.height) { hitArea.height = this.renderer.height - hitArea.y; } }; /** * Adds a DisplayObject to the accessibility manager * * @private * @param {PIXI.DisplayObject} displayObject - The child to make accessible. */ AccessibilityManager.prototype.addChild = function addChild (displayObject) { //this.activate(); var div = this.pool.pop(); if (!div) { div = document.createElement('button'); div.style.width = DIV_TOUCH_SIZE + "px"; div.style.height = DIV_TOUCH_SIZE + "px"; div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent'; div.style.position = 'absolute'; div.style.zIndex = DIV_TOUCH_ZINDEX; div.style.borderStyle = 'none'; // ARIA attributes ensure that button title and hint updates are announced properly if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. div.setAttribute('aria-live', 'off'); } else { div.setAttribute('aria-live', 'polite'); } if (navigator.userAgent.match(/rv:.*Gecko\//)) { // FireFox needs this to announce only the new button name div.setAttribute('aria-relevant', 'additions'); } else { // required by IE, other browsers don't much care div.setAttribute('aria-relevant', 'text'); } div.addEventListener('click', this._onClick.bind(this)); div.addEventListener('focus', this._onFocus.bind(this)); div.addEventListener('focusout', this._onFocusOut.bind(this)); } // set pointer events div.style.pointerEvents = displayObject.accessiblePointerEvents; // set the type, this defaults to button! div.type = displayObject.accessibleType; if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { div.title = displayObject.accessibleTitle; } else if (!displayObject.accessibleHint || displayObject.accessibleHint === null) { div.title = "displayObject " + (displayObject.tabIndex); } if (displayObject.accessibleHint && displayObject.accessibleHint !== null) { div.setAttribute('aria-label', displayObject.accessibleHint); } if (this.debug) { this.updateDebugHTML(div); } displayObject._accessibleActive = true; displayObject._accessibleDiv = div; div.displayObject = displayObject; this.children.push(displayObject); this.div.appendChild(displayObject._accessibleDiv); displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; }; /** * Maps the div button press to pixi's InteractionManager (click) * * @private * @param {MouseEvent} e - The click event. */ AccessibilityManager.prototype._onClick = function _onClick (e) { var interactionManager = this.renderer.plugins.interaction; interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); interactionManager.dispatchEvent(e.target.displayObject, 'pointertap', interactionManager.eventData); interactionManager.dispatchEvent(e.target.displayObject, 'tap', interactionManager.eventData); }; /** * Maps the div focus events to pixi's InteractionManager (mouseover) * * @private * @param {FocusEvent} e - The focus event. */ AccessibilityManager.prototype._onFocus = function _onFocus (e) { if (!e.target.getAttribute('aria-live', 'off')) { e.target.setAttribute('aria-live', 'assertive'); } var interactionManager = this.renderer.plugins.interaction; interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); }; /** * Maps the div focus events to pixi's InteractionManager (mouseout) * * @private * @param {FocusEvent} e - The focusout event. */ AccessibilityManager.prototype._onFocusOut = function _onFocusOut (e) { if (!e.target.getAttribute('aria-live', 'off')) { e.target.setAttribute('aria-live', 'polite'); } var interactionManager = this.renderer.plugins.interaction; interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); }; /** * Is called when a key is pressed * * @private * @param {KeyboardEvent} e - The keydown event. */ AccessibilityManager.prototype._onKeyDown = function _onKeyDown (e) { if (e.keyCode !== KEY_CODE_TAB) { return; } this.activate(); }; /** * Is called when the mouse moves across the renderer element * * @private * @param {MouseEvent} e - The mouse event. */ AccessibilityManager.prototype._onMouseMove = function _onMouseMove (e) { if (e.movementX === 0 && e.movementY === 0) { return; } this.deactivate(); }; /** * Destroys the accessibility manager * */ AccessibilityManager.prototype.destroy = function destroy () { this.destroyTouchHook(); this.div = null; for (var i = 0; i < this.children.length; i++) { this.children[i].div = null; } window.document.removeEventListener('mousemove', this._onMouseMove, true); window.removeEventListener('keydown', this._onKeyDown); this.pool = null; this.children = null; this.renderer = null; }; /** * This namespace contains an accessibility plugin for allowing interaction via the keyboard. * * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. * @namespace PIXI.accessibility */ exports.AccessibilityManager = AccessibilityManager; exports.accessibleTarget = accessibleTarget; },{"@pixi/display":8,"@pixi/utils":39}],5:[function(require,module,exports){ /*! * @pixi/app - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/app is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var display = require('@pixi/display'); var core = require('@pixi/core'); /** * Convenience class to create a new PIXI application. * * This class automatically creates the renderer, ticker and root container. * * @example * // Create the application * const app = new PIXI.Application(); * * // Add the view to the DOM * document.body.appendChild(app.view); * * // ex, add display objects * app.stage.addChild(PIXI.Sprite.from('something.png')); * * @class * @memberof PIXI */ var Application = function Application(options) { var this$1 = this; // The default options options = Object.assign({ forceCanvas: false, }, options); /** * WebGL renderer if available, otherwise CanvasRenderer. * @member {PIXI.Renderer|PIXI.CanvasRenderer} */ this.renderer = core.autoDetectRenderer(options); /** * The root display container that's rendered. * @member {PIXI.Container} */ this.stage = new display.Container(); // install plugins here Application._plugins.forEach(function (plugin) { plugin.init.call(this$1, options); }); }; var prototypeAccessors = { view: { configurable: true },screen: { configurable: true } }; /** * Register a middleware plugin for the application * @static * @param {PIXI.Application.Plugin} plugin - Plugin being installed */ Application.registerPlugin = function registerPlugin (plugin) { Application._plugins.push(plugin); }; /** * Render the current stage. */ Application.prototype.render = function render () { this.renderer.render(this.stage); }; /** * Reference to the renderer's canvas element. * @member {HTMLCanvasElement} * @readonly */ prototypeAccessors.view.get = function () { return this.renderer.view; }; /** * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen. * @member {PIXI.Rectangle} * @readonly */ prototypeAccessors.screen.get = function () { return this.renderer.screen; }; /** * Destroy and don't use after this. * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options * have been set to that value * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy * method called as well. 'stageOptions' will be passed on to those calls. * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set * to true. Should it destroy the texture of the child sprite * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set * to true. Should it destroy the base texture of the child sprite */ Application.prototype.destroy = function destroy (removeView, stageOptions) { var this$1 = this; // Destroy plugins in the opposite order // which they were constructed var plugins = Application._plugins.slice(0); plugins.reverse(); plugins.forEach(function (plugin) { plugin.destroy.call(this$1); }); this.stage.destroy(stageOptions); this.stage = null; this.renderer.destroy(removeView); this.renderer = null; this._options = null; }; Object.defineProperties( Application.prototype, prototypeAccessors ); /** * @memberof PIXI.Application * @typedef {object} Plugin * @property {function} init - Called when Application is constructed, scoped to Application instance. * Passes in `options` as the only argument, which are Application constructor options. * @property {function} destroy - Called when destroying Application, scoped to Application instance */ /** * Collection of installed plugins. * @static * @private * @type {PIXI.Application.Plugin[]} */ Application._plugins = []; /** * Middleware for for Application's resize functionality * @private * @class */ var ResizePlugin = function ResizePlugin () {}; ResizePlugin.init = function init (options) { var this$1 = this; /** * The element or window to resize the application to. * @type {Window|HTMLElement} * @name resizeTo * @memberof PIXI.Application# */ Object.defineProperty(this, 'resizeTo', { set: function set(dom) { window.removeEventListener('resize', this.resize); this._resizeTo = dom; if (dom) { window.addEventListener('resize', this.resize); this.resize(); } }, get: function get() { return this._resizeTo; }, }); /** * If `resizeTo` is set, calling this function * will resize to the width and height of that element. * @method PIXI.Application#resize */ this.resize = function () { if (this$1._resizeTo) { // Resize to the window if (this$1._resizeTo === window) { this$1.renderer.resize( window.innerWidth, window.innerHeight ); } // Resize to other HTML entities else { this$1.renderer.resize( this$1._resizeTo.clientWidth, this$1._resizeTo.clientHeight ); } } }; // On resize this._resizeTo = null; this.resizeTo = options.resizeTo || null; }; /** * Clean up the ticker, scoped to application * @static * @private */ ResizePlugin.destroy = function destroy () { this.resizeTo = null; this.resize = null; }; Application.registerPlugin(ResizePlugin); exports.Application = Application; },{"@pixi/core":7,"@pixi/display":8}],6:[function(require,module,exports){ /*! * @pixi/constants - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/constants is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * Different types of environments for WebGL. * * @static * @memberof PIXI * @name ENV * @enum {number} * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility * with older / less advanced devices. If you experience unexplained flickering prefer this environment. * @property {number} WEBGL - Version 1 of WebGL * @property {number} WEBGL2 - Version 2 of WebGL */ (function (ENV) { ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; ENV[ENV["WEBGL"] = 1] = "WEBGL"; ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; })(exports.ENV || (exports.ENV = {})); (function (RENDERER_TYPE) { RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; })(exports.RENDERER_TYPE || (exports.RENDERER_TYPE = {})); (function (BLEND_MODES) { BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; })(exports.BLEND_MODES || (exports.BLEND_MODES = {})); (function (DRAW_MODES) { DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; })(exports.DRAW_MODES || (exports.DRAW_MODES = {})); (function (FORMATS) { FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; FORMATS[FORMATS["RGB"] = 6407] = "RGB"; FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; })(exports.FORMATS || (exports.FORMATS = {})); (function (TARGETS) { TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; })(exports.TARGETS || (exports.TARGETS = {})); (function (TYPES) { TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; })(exports.TYPES || (exports.TYPES = {})); (function (SCALE_MODES) { SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; })(exports.SCALE_MODES || (exports.SCALE_MODES = {})); (function (WRAP_MODES) { WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; })(exports.WRAP_MODES || (exports.WRAP_MODES = {})); (function (MIPMAP_MODES) { MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; })(exports.MIPMAP_MODES || (exports.MIPMAP_MODES = {})); (function (ALPHA_MODES) { ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; })(exports.ALPHA_MODES || (exports.ALPHA_MODES = {})); (function (GC_MODES) { GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; })(exports.GC_MODES || (exports.GC_MODES = {})); (function (PRECISION) { PRECISION["LOW"] = "lowp"; PRECISION["MEDIUM"] = "mediump"; PRECISION["HIGH"] = "highp"; })(exports.PRECISION || (exports.PRECISION = {})); (function (MASK_TYPES) { MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; })(exports.MASK_TYPES || (exports.MASK_TYPES = {})); },{}],7:[function(require,module,exports){ /*! * @pixi/core - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/core is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var runner = require('@pixi/runner'); var utils = require('@pixi/utils'); var constants = require('@pixi/constants'); var settings = require('@pixi/settings'); var ticker = require('@pixi/ticker'); var math = require('@pixi/math'); var display = require('@pixi/display'); /** * Base resource class for textures that manages validation and uploading, depending on its type. * * Uploading of a base texture to the GPU is required. * * @class * @memberof PIXI.resources */ var Resource = function Resource(width, height) { if ( width === void 0 ) width = 0; if ( height === void 0 ) height = 0; /** * Internal width of the resource * @member {number} * @protected */ this._width = width; /** * Internal height of the resource * @member {number} * @protected */ this._height = height; /** * If resource has been destroyed * @member {boolean} * @readonly * @default false */ this.destroyed = false; /** * `true` if resource is created by BaseTexture * useful for doing cleanup with BaseTexture destroy * and not cleaning up resources that were created * externally. * @member {boolean} * @protected */ this.internal = false; /** * Mini-runner for handling resize events * * @member {Runner} * @private */ this.onResize = new runner.Runner('setRealSize', 2); /** * Mini-runner for handling update events * * @member {Runner} * @private */ this.onUpdate = new runner.Runner('update'); /** * Handle internal errors, such as loading errors * * @member {Runner} * @private */ this.onError = new runner.Runner('onError', 1); }; var prototypeAccessors = { valid: { configurable: true },width: { configurable: true },height: { configurable: true } }; /** * Bind to a parent BaseTexture * * @param {PIXI.BaseTexture} baseTexture - Parent texture */ Resource.prototype.bind = function bind (baseTexture) { this.onResize.add(baseTexture); this.onUpdate.add(baseTexture); this.onError.add(baseTexture); // Call a resize immediate if we already // have the width and height of the resource if (this._width || this._height) { this.onResize.run(this._width, this._height); } }; /** * Unbind to a parent BaseTexture * * @param {PIXI.BaseTexture} baseTexture - Parent texture */ Resource.prototype.unbind = function unbind (baseTexture) { this.onResize.remove(baseTexture); this.onUpdate.remove(baseTexture); this.onError.remove(baseTexture); }; /** * Trigger a resize event * @param {number} width X dimension * @param {number} height Y dimension */ Resource.prototype.resize = function resize (width, height) { if (width !== this._width || height !== this._height) { this._width = width; this._height = height; this.onResize.run(width, height); } }; /** * Has been validated * @readonly * @member {boolean} */ prototypeAccessors.valid.get = function () { return !!this._width && !!this._height; }; /** * Has been updated trigger event */ Resource.prototype.update = function update () { if (!this.destroyed) { this.onUpdate.run(); } }; /** * This can be overridden to start preloading a resource * or do any other prepare step. * @protected * @return {Promise} Handle the validate event */ Resource.prototype.load = function load () { return Promise.resolve(); }; /** * The width of the resource. * * @member {number} * @readonly */ prototypeAccessors.width.get = function () { return this._width; }; /** * The height of the resource. * * @member {number} * @readonly */ prototypeAccessors.height.get = function () { return this._height; }; /** * Uploads the texture or returns false if it cant for some reason. Override this. * * @param {PIXI.Renderer} renderer - yeah, renderer! * @param {PIXI.BaseTexture} baseTexture - the texture * @param {PIXI.GLTexture} glTexture - texture instance for this webgl context * @returns {boolean} true is success */ Resource.prototype.upload = function upload (renderer, baseTexture, glTexture) // eslint-disable-line no-unused-vars { return false; }; /** * Set the style, optional to override * * @param {PIXI.Renderer} renderer - yeah, renderer! * @param {PIXI.BaseTexture} baseTexture - the texture * @param {PIXI.GLTexture} glTexture - texture instance for this webgl context * @returns {boolean} `true` is success */ Resource.prototype.style = function style (renderer, baseTexture, glTexture) // eslint-disable-line no-unused-vars { return false; }; /** * Clean up anything, this happens when destroying is ready. * * @protected */ Resource.prototype.dispose = function dispose () { // override }; /** * Call when destroying resource, unbind any BaseTexture object * before calling this method, as reference counts are maintained * internally. */ Resource.prototype.destroy = function destroy () { if (!this.destroyed) { this.destroyed = true; this.dispose(); this.onError.removeAll(); this.onError = null; this.onResize.removeAll(); this.onResize = null; this.onUpdate.removeAll(); this.onUpdate = null; } }; Object.defineProperties( Resource.prototype, prototypeAccessors ); /** * Base for all the image/canvas resources * @class * @extends PIXI.resources.Resource * @memberof PIXI.resources */ var BaseImageResource = /*@__PURE__*/(function (Resource) { function BaseImageResource(source) { var width = source.naturalWidth || source.videoWidth || source.width; var height = source.naturalHeight || source.videoHeight || source.height; Resource.call(this, width, height); /** * The source element * @member {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} * @readonly */ this.source = source; /** * If set to `true`, will force `texImage2D` over `texSubImage2D` for uploading. * Certain types of media (e.g. video) using `texImage2D` is more performant. * @member {boolean} * @default false * @private */ this.noSubImage = false; } if ( Resource ) BaseImageResource.__proto__ = Resource; BaseImageResource.prototype = Object.create( Resource && Resource.prototype ); BaseImageResource.prototype.constructor = BaseImageResource; /** * Set cross origin based detecting the url and the crossorigin * @protected * @param {HTMLElement} element - Element to apply crossOrigin * @param {string} url - URL to check * @param {boolean|string} [crossorigin=true] - Cross origin value to use */ BaseImageResource.crossOrigin = function crossOrigin (element, url, crossorigin) { if (crossorigin === undefined && url.indexOf('data:') !== 0) { element.crossOrigin = utils.determineCrossOrigin(url); } else if (crossorigin !== false) { element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; } }; /** * Upload the texture to the GPU. * @param {PIXI.Renderer} renderer Upload to the renderer * @param {PIXI.BaseTexture} baseTexture Reference to parent texture * @param {PIXI.GLTexture} glTexture * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] (optional) * @returns {boolean} true is success */ BaseImageResource.prototype.upload = function upload (renderer, baseTexture, glTexture, source) { var gl = renderer.gl; var width = baseTexture.realWidth; var height = baseTexture.realHeight; source = source || this.source; gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants.ALPHA_MODES.UNPACK); if (!this.noSubImage && baseTexture.target === gl.TEXTURE_2D && glTexture.width === width && glTexture.height === height) { gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, baseTexture.type, source); } else { glTexture.width = width; glTexture.height = height; gl.texImage2D(baseTexture.target, 0, baseTexture.format, baseTexture.format, baseTexture.type, source); } return true; }; /** * Checks if source width/height was changed, resize can cause extra baseTexture update. * Triggers one update in any case. */ BaseImageResource.prototype.update = function update () { if (this.destroyed) { return; } var width = this.source.naturalWidth || this.source.videoWidth || this.source.width; var height = this.source.naturalHeight || this.source.videoHeight || this.source.height; this.resize(width, height); Resource.prototype.update.call(this); }; /** * Destroy this BaseImageResource * @override * @param {PIXI.BaseTexture} [fromTexture] Optional base texture * @return {boolean} Destroy was successful */ BaseImageResource.prototype.dispose = function dispose () { this.source = null; }; return BaseImageResource; }(Resource)); /** * Resource type for HTMLImageElement. * @class * @extends PIXI.resources.BaseImageResource * @memberof PIXI.resources */ var ImageResource = /*@__PURE__*/(function (BaseImageResource) { function ImageResource(source, options) { options = options || {}; if (!(source instanceof HTMLImageElement)) { var imageElement = new Image(); BaseImageResource.crossOrigin(imageElement, source, options.crossorigin); imageElement.src = source; source = imageElement; } BaseImageResource.call(this, source); // FireFox 68, and possibly other versions, seems like setting the HTMLImageElement#width and #height // to non-zero values before its loading completes if images are in a cache. // Because of this, need to set the `_width` and the `_height` to zero to avoid uploading incomplete images. // Please refer to the issue #5968 (https://github.com/pixijs/pixi.js/issues/5968). if (!source.complete && !!this._width && !!this._height) { this._width = 0; this._height = 0; } /** * URL of the image source * @member {string} */ this.url = source.src; /** * When process is completed * @member {Promise} * @private */ this._process = null; /** * If the image should be disposed after upload * @member {boolean} * @default false */ this.preserveBitmap = false; /** * If capable, convert the image using createImageBitmap API * @member {boolean} * @default PIXI.settings.CREATE_IMAGE_BITMAP */ this.createBitmap = (options.createBitmap !== undefined ? options.createBitmap : settings.settings.CREATE_IMAGE_BITMAP) && !!window.createImageBitmap; /** * Controls texture alphaMode field * Copies from options * Default is `null`, copies option from baseTexture * * @member {PIXI.ALPHA_MODES|null} * @readonly */ this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null; if (options.premultiplyAlpha !== undefined) { // triggers deprecation this.premultiplyAlpha = options.premultiplyAlpha; } /** * The ImageBitmap element created for HTMLImageElement * @member {ImageBitmap} * @default null */ this.bitmap = null; /** * Promise when loading * @member {Promise} * @private * @default null */ this._load = null; if (options.autoLoad !== false) { this.load(); } } if ( BaseImageResource ) ImageResource.__proto__ = BaseImageResource; ImageResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype ); ImageResource.prototype.constructor = ImageResource; /** * returns a promise when image will be loaded and processed * * @param {boolean} [createBitmap=true] whether process image into bitmap * @returns {Promise} */ ImageResource.prototype.load = function load (createBitmap) { var this$1 = this; if (createBitmap !== undefined) { this.createBitmap = createBitmap; } if (this._load) { return this._load; } this._load = new Promise(function (resolve) { this$1.url = this$1.source.src; var ref = this$1; var source = ref.source; var completed = function () { if (this$1.destroyed) { return; } source.onload = null; source.onerror = null; this$1.resize(source.width, source.height); this$1._load = null; if (this$1.createBitmap) { resolve(this$1.process()); } else { resolve(this$1); } }; if (source.complete && source.src) { completed(); } else { source.onload = completed; source.onerror = function (event) { return this$1.onError.run(event); }; } }); return this._load; }; /** * Called when we need to convert image into BitmapImage. * Can be called multiple times, real promise is cached inside. * * @returns {Promise} cached promise to fill that bitmap */ ImageResource.prototype.process = function process () { var this$1 = this; if (this._process !== null) { return this._process; } if (this.bitmap !== null || !window.createImageBitmap) { return Promise.resolve(this); } this._process = window.createImageBitmap(this.source, 0, 0, this.source.width, this.source.height, { premultiplyAlpha: this.premultiplyAlpha === constants.ALPHA_MODES.UNPACK ? 'premultiply' : 'none', }) .then(function (bitmap) { if (this$1.destroyed) { return Promise.reject(); } this$1.bitmap = bitmap; this$1.update(); this$1._process = null; return Promise.resolve(this$1); }); return this._process; }; /** * Upload the image resource to GPU. * * @param {PIXI.Renderer} renderer - Renderer to upload to * @param {PIXI.BaseTexture} baseTexture - BaseTexture for this resource * @param {PIXI.GLTexture} glTexture - GLTexture to use * @returns {boolean} true is success */ ImageResource.prototype.upload = function upload (renderer, baseTexture, glTexture) { if (typeof this.alphaMode === 'number') { // bitmap stores unpack premultiply flag, we dont have to notify texImage2D about it baseTexture.alphaMode = this.alphaMode; } if (!this.createBitmap) { return BaseImageResource.prototype.upload.call(this, renderer, baseTexture, glTexture); } if (!this.bitmap) { // yeah, ignore the output this.process(); if (!this.bitmap) { return false; } } BaseImageResource.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap); if (!this.preserveBitmap) { // checks if there are other renderers that possibly need this bitmap var flag = true; for (var key in baseTexture._glTextures) { var otherTex = baseTexture._glTextures[key]; if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) { flag = false; break; } } if (flag) { if (this.bitmap.close) { this.bitmap.close(); } this.bitmap = null; } } return true; }; /** * Destroys this texture * @override */ ImageResource.prototype.dispose = function dispose () { this.source.onload = null; this.source.onerror = null; BaseImageResource.prototype.dispose.call(this); if (this.bitmap) { this.bitmap.close(); this.bitmap = null; } this._process = null; this._load = null; }; return ImageResource; }(BaseImageResource)); /** * Collection of installed resource types, class must extend {@link PIXI.resources.Resource}. * @example * class CustomResource extends PIXI.resources.Resource { * // MUST have source, options constructor signature * // for auto-detected resources to be created. * constructor(source, options) { * super(); * } * upload(renderer, baseTexture, glTexture) { * // upload with GL * return true; * } * // used to auto-detect resource * static test(source, extension) { * return extension === 'xyz'|| source instanceof SomeClass; * } * } * // Install the new resource type * PIXI.resources.INSTALLED.push(CustomResource); * * @name PIXI.resources.INSTALLED * @type {Array<*>} * @static * @readonly */ var INSTALLED = []; /** * Create a resource element from a single source element. This * auto-detects which type of resource to create. All resources that * are auto-detectable must have a static `test` method and a constructor * with the arguments `(source, options?)`. Currently, the supported * resources for auto-detection include: * - {@link PIXI.resources.ImageResource} * - {@link PIXI.resources.CanvasResource} * - {@link PIXI.resources.VideoResource} * - {@link PIXI.resources.SVGResource} * - {@link PIXI.resources.BufferResource} * @static * @function PIXI.resources.autoDetectResource * @param {string|*} source - Resource source, this can be the URL to the resource, * a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri * or any other resource that can be auto-detected. If not resource is * detected, it's assumed to be an ImageResource. * @param {object} [options] - Pass-through options to use for Resource * @param {number} [options.width] - Width of BufferResource or SVG rasterization * @param {number} [options.height] - Height of BufferResource or SVG rasterization * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading * @param {number} [options.scale=1] - SVG source scale. Overridden by width, height * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately * @param {number} [options.updateFPS=0] - Video option to update how many times a second the * texture should be updated from the video. Leave at 0 to update at every render * @return {PIXI.resources.Resource} The created resource. */ function autoDetectResource(source, options) { if (!source) { return null; } var extension = ''; if (typeof source === 'string') { // search for file extension: period, 3-4 chars, then ?, # or EOL var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source); if (result) { extension = result[1].toLowerCase(); } } for (var i = INSTALLED.length - 1; i >= 0; --i) { var ResourcePlugin = INSTALLED[i]; if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) { return new ResourcePlugin(source, options); } } // When in doubt: probably an image // might be appropriate to throw an error or return null return new ImageResource(source, options); } /** * @interface SharedArrayBuffer */ /** * Buffer resource with data of typed array. * @class * @extends PIXI.resources.Resource * @memberof PIXI.resources */ var BufferResource = /*@__PURE__*/(function (Resource) { function BufferResource(source, options) { var ref = options || {}; var width = ref.width; var height = ref.height; if (!width || !height) { throw new Error('BufferResource width or height invalid'); } Resource.call(this, width, height); /** * Source array * Cannot be ClampedUint8Array because it cant be uploaded to WebGL * * @member {Float32Array|Uint8Array|Uint32Array} */ this.data = source; } if ( Resource ) BufferResource.__proto__ = Resource; BufferResource.prototype = Object.create( Resource && Resource.prototype ); BufferResource.prototype.constructor = BufferResource; /** * Upload the texture to the GPU. * @param {PIXI.Renderer} renderer Upload to the renderer * @param {PIXI.BaseTexture} baseTexture Reference to parent texture * @param {PIXI.GLTexture} glTexture glTexture * @returns {boolean} true is success */ BufferResource.prototype.upload = function upload (renderer, baseTexture, glTexture) { var gl = renderer.gl; gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants.ALPHA_MODES.UNPACK); if (glTexture.width === baseTexture.width && glTexture.height === baseTexture.height) { gl.texSubImage2D( baseTexture.target, 0, 0, 0, baseTexture.width, baseTexture.height, baseTexture.format, baseTexture.type, this.data ); } else { glTexture.width = baseTexture.width; glTexture.height = baseTexture.height; gl.texImage2D( baseTexture.target, 0, glTexture.internalFormat, baseTexture.width, baseTexture.height, 0, baseTexture.format, glTexture.type, this.data ); } return true; }; /** * Destroy and don't use after this * @override */ BufferResource.prototype.dispose = function dispose () { this.data = null; }; /** * Used to auto-detect the type of resource. * * @static * @param {*} source - The source object * @return {boolean} `true` if */ BufferResource.test = function test (source) { return source instanceof Float32Array || source instanceof Uint8Array || source instanceof Uint32Array; }; return BufferResource; }(Resource)); var defaultBufferOptions = { scaleMode: constants.SCALE_MODES.NEAREST, format: constants.FORMATS.RGBA, alphaMode: constants.ALPHA_MODES.NPM, }; /** * A Texture stores the information that represents an image. * All textures have a base texture, which contains information about the source. * Therefore you can have many textures all using a single BaseTexture * * @class * @extends PIXI.utils.EventEmitter * @memberof PIXI * @param {PIXI.resources.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null] * The current resource to use, for things that aren't Resource objects, will be converted * into a Resource. * @param {Object} [options] - Collection of options * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture * @param {number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha * @param {number} [options.width=0] - Width of the texture * @param {number} [options.height=0] - Height of the texture * @param {number} [options.resolution] - Resolution of the base texture * @param {object} [options.resourceOptions] - Optional resource options, * see {@link PIXI.resources.autoDetectResource autoDetectResource} */ var BaseTexture = /*@__PURE__*/(function (EventEmitter) { function BaseTexture(resource, options) { if ( resource === void 0 ) resource = null; if ( options === void 0 ) options = null; EventEmitter.call(this); options = options || {}; var alphaMode = options.alphaMode; var mipmap = options.mipmap; var anisotropicLevel = options.anisotropicLevel; var scaleMode = options.scaleMode; var width = options.width; var height = options.height; var wrapMode = options.wrapMode; var format = options.format; var type = options.type; var target = options.target; var resolution = options.resolution; var resourceOptions = options.resourceOptions; // Convert the resource to a Resource object if (resource && !(resource instanceof Resource)) { resource = autoDetectResource(resource, resourceOptions); resource.internal = true; } /** * The width of the base texture set when the image has loaded * * @readonly * @member {number} */ this.width = width || 0; /** * The height of the base texture set when the image has loaded * * @readonly * @member {number} */ this.height = height || 0; /** * The resolution / device pixel ratio of the texture * * @member {number} * @default PIXI.settings.RESOLUTION */ this.resolution = resolution || settings.settings.RESOLUTION; /** * Mipmap mode of the texture, affects downscaled images * * @member {PIXI.MIPMAP_MODES} * @default PIXI.settings.MIPMAP_TEXTURES */ this.mipmap = mipmap !== undefined ? mipmap : settings.settings.MIPMAP_TEXTURES; /** * Anisotropic filtering level of texture * * @member {number} * @default PIXI.settings.ANISOTROPIC_LEVEL */ this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings.settings.ANISOTROPIC_LEVEL; /** * How the texture wraps * @member {number} */ this.wrapMode = wrapMode || settings.settings.WRAP_MODE; /** * The scale mode to apply when scaling this texture * * @member {PIXI.SCALE_MODES} * @default PIXI.settings.SCALE_MODE */ this.scaleMode = scaleMode !== undefined ? scaleMode : settings.settings.SCALE_MODE; /** * The pixel format of the texture * * @member {PIXI.FORMATS} * @default PIXI.FORMATS.RGBA */ this.format = format || constants.FORMATS.RGBA; /** * The type of resource data * * @member {PIXI.TYPES} * @default PIXI.TYPES.UNSIGNED_BYTE */ this.type = type || constants.TYPES.UNSIGNED_BYTE; /** * The target type * * @member {PIXI.TARGETS} * @default PIXI.TARGETS.TEXTURE_2D */ this.target = target || constants.TARGETS.TEXTURE_2D; /** * How to treat premultiplied alpha, see {@link PIXI.ALPHA_MODES}. * * @member {PIXI.ALPHA_MODES} * @default PIXI.ALPHA_MODES.UNPACK */ this.alphaMode = alphaMode !== undefined ? alphaMode : constants.ALPHA_MODES.UNPACK; if (options.premultiplyAlpha !== undefined) { // triggers deprecation this.premultiplyAlpha = options.premultiplyAlpha; } /** * Global unique identifier for this BaseTexture * * @member {string} * @protected */ this.uid = utils.uid(); /** * Used by automatic texture Garbage Collection, stores last GC tick when it was bound * * @member {number} * @protected */ this.touched = 0; /** * Whether or not the texture is a power of two, try to use power of two textures as much * as you can * * @readonly * @member {boolean} * @default false */ this.isPowerOfTwo = false; this._refreshPOT(); /** * The map of render context textures where this is bound * * @member {Object} * @private */ this._glTextures = {}; /** * Used by TextureSystem to only update texture to the GPU when needed. * Please call `update()` to increment it. * * @readonly * @member {number} */ this.dirtyId = 0; /** * Used by TextureSystem to only update texture style when needed. * * @protected * @member {number} */ this.dirtyStyleId = 0; /** * Currently default cache ID. * * @member {string} */ this.cacheId = null; /** * Generally speaking means when resource is loaded. * @readonly * @member {boolean} */ this.valid = width > 0 && height > 0; /** * The collection of alternative cache ids, since some BaseTextures * can have more than one ID, short name and longer full URL * * @member {Array} * @readonly */ this.textureCacheIds = []; /** * Flag if BaseTexture has been destroyed. * * @member {boolean} * @readonly */ this.destroyed = false; /** * The resource used by this BaseTexture, there can only * be one resource per BaseTexture, but textures can share * resources. * * @member {PIXI.resources.Resource} * @readonly */ this.resource = null; /** * Number of the texture batch, used by multi-texture renderers * * @member {number} */ this._batchEnabled = 0; /** * Location inside texture batch, used by multi-texture renderers * * @member {number} */ this._batchLocation = 0; /** * Fired when a not-immediately-available source finishes loading. * * @protected * @event PIXI.BaseTexture#loaded * @param {PIXI.BaseTexture} baseTexture - Resource loaded. */ /** * Fired when a not-immediately-available source fails to load. * * @protected * @event PIXI.BaseTexture#error * @param {PIXI.BaseTexture} baseTexture - Resource errored. * @param {ErrorEvent} event - Load error event. */ /** * Fired when BaseTexture is updated. * * @protected * @event PIXI.BaseTexture#loaded * @param {PIXI.BaseTexture} baseTexture - Resource loaded. */ /** * Fired when BaseTexture is updated. * * @protected * @event PIXI.BaseTexture#update * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. */ /** * Fired when BaseTexture is destroyed. * * @protected * @event PIXI.BaseTexture#dispose * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. */ // Set the resource this.setResource(resource); } if ( EventEmitter ) BaseTexture.__proto__ = EventEmitter; BaseTexture.prototype = Object.create( EventEmitter && EventEmitter.prototype ); BaseTexture.prototype.constructor = BaseTexture; var prototypeAccessors = { realWidth: { configurable: true },realHeight: { configurable: true } }; /** * Pixel width of the source of this texture * * @readonly * @member {number} */ prototypeAccessors.realWidth.get = function () { return Math.ceil((this.width * this.resolution) - 1e-4); }; /** * Pixel height of the source of this texture * * @readonly * @member {number} */ prototypeAccessors.realHeight.get = function () { return Math.ceil((this.height * this.resolution) - 1e-4); }; /** * Changes style options of BaseTexture * * @param {PIXI.SCALE_MODES} [scaleMode] - Pixi scalemode * @param {PIXI.MIPMAP_MODES} [mipmap] - enable mipmaps * @returns {PIXI.BaseTexture} this */ BaseTexture.prototype.setStyle = function setStyle (scaleMode, mipmap) { var dirty; if (scaleMode !== undefined && scaleMode !== this.scaleMode) { this.scaleMode = scaleMode; dirty = true; } if (mipmap !== undefined && mipmap !== this.mipmap) { this.mipmap = mipmap; dirty = true; } if (dirty) { this.dirtyStyleId++; } return this; }; /** * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero. * * @param {number} width Visual width * @param {number} height Visual height * @param {number} [resolution] Optionally set resolution * @returns {PIXI.BaseTexture} this */ BaseTexture.prototype.setSize = function setSize (width, height, resolution) { this.resolution = resolution || this.resolution; this.width = width; this.height = height; this._refreshPOT(); this.update(); return this; }; /** * Sets real size of baseTexture, preserves current resolution. * * @param {number} realWidth Full rendered width * @param {number} realHeight Full rendered height * @param {number} [resolution] Optionally set resolution * @returns {PIXI.BaseTexture} this */ BaseTexture.prototype.setRealSize = function setRealSize (realWidth, realHeight, resolution) { this.resolution = resolution || this.resolution; this.width = realWidth / this.resolution; this.height = realHeight / this.resolution; this._refreshPOT(); this.update(); return this; }; /** * Refresh check for isPowerOfTwo texture based on size * * @private */ BaseTexture.prototype._refreshPOT = function _refreshPOT () { this.isPowerOfTwo = utils.isPow2(this.realWidth) && utils.isPow2(this.realHeight); }; /** * Changes resolution * * @param {number} [resolution] res * @returns {PIXI.BaseTexture} this */ BaseTexture.prototype.setResolution = function setResolution (resolution) { var oldResolution = this.resolution; if (oldResolution === resolution) { return this; } this.resolution = resolution; if (this.valid) { this.width = this.width * oldResolution / resolution; this.height = this.height * oldResolution / resolution; this.emit('update', this); } this._refreshPOT(); return this; }; /** * Sets the resource if it wasn't set. Throws error if resource already present * * @param {PIXI.resources.Resource} resource - that is managing this BaseTexture * @returns {PIXI.BaseTexture} this */ BaseTexture.prototype.setResource = function setResource (resource) { if (this.resource === resource) { return this; } if (this.resource) { throw new Error('Resource can be set only once'); } resource.bind(this); this.resource = resource; return this; }; /** * Invalidates the object. Texture becomes valid if width and height are greater than zero. */ BaseTexture.prototype.update = function update () { if (!this.valid) { if (this.width > 0 && this.height > 0) { this.valid = true; this.emit('loaded', this); this.emit('update', this); } } else { this.dirtyId++; this.dirtyStyleId++; this.emit('update', this); } }; /** * Handle errors with resources. * @private * @param {ErrorEvent} event - Error event emitted. */ BaseTexture.prototype.onError = function onError (event) { this.emit('error', this, event); }; /** * Destroys this base texture. * The method stops if resource doesn't want this texture to be destroyed. * Removes texture from all caches. */ BaseTexture.prototype.destroy = function destroy () { // remove and destroy the resource if (this.resource) { this.resource.unbind(this); // only destroy resourced created internally if (this.resource.internal) { this.resource.destroy(); } this.resource = null; } if (this.cacheId) { delete utils.BaseTextureCache[this.cacheId]; delete utils.TextureCache[this.cacheId]; this.cacheId = null; } // finally let the WebGL renderer know.. this.dispose(); BaseTexture.removeFromCache(this); this.textureCacheIds = null; this.destroyed = true; }; /** * Frees the texture from WebGL memory without destroying this texture object. * This means you can still use the texture later which will upload it to GPU * memory again. * * @fires PIXI.BaseTexture#dispose */ BaseTexture.prototype.dispose = function dispose () { this.emit('dispose', this); }; /** * Helper function that creates a base texture based on the source you provide. * The source can be - image url, image element, canvas element. If the * source is an image url or an image element and not in the base texture * cache, it will be created and loaded. * * @static * @param {string|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The * source to create base texture from. * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. * @param {boolean} [strict] Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. * @returns {PIXI.BaseTexture} The new base texture. */ BaseTexture.from = function from (source, options, strict) { if ( strict === void 0 ) strict = settings.settings.STRICT_TEXTURE_CACHE; var isFrame = typeof source === 'string'; var cacheId = null; if (isFrame) { cacheId = source; } else { if (!source._pixiId) { source._pixiId = "pixiid_" + (utils.uid()); } cacheId = source._pixiId; } var baseTexture = utils.BaseTextureCache[cacheId]; // Strict-mode rejects invalid cacheIds if (isFrame && strict && !baseTexture) { throw new Error(("The cacheId \"" + cacheId + "\" does not exist in BaseTextureCache.")); } if (!baseTexture) { baseTexture = new BaseTexture(source, options); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } return baseTexture; }; /** * Create a new BaseTexture with a BufferResource from a Float32Array. * RGBA values are floats from 0 to 1. * @static * @param {Float32Array|Uint8Array} buffer The optional array to use, if no data * is provided, a new Float32Array is created. * @param {number} width - Width of the resource * @param {number} height - Height of the resource * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. * @return {PIXI.BaseTexture} The resulting new BaseTexture */ BaseTexture.fromBuffer = function fromBuffer (buffer, width, height, options) { buffer = buffer || new Float32Array(width * height * 4); var resource = new BufferResource(buffer, { width: width, height: height }); var type = buffer instanceof Float32Array ? constants.TYPES.FLOAT : constants.TYPES.UNSIGNED_BYTE; return new BaseTexture(resource, Object.assign(defaultBufferOptions, options || { width: width, height: height, type: type })); }; /** * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. * * @static * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. * @param {string} id - The id that the BaseTexture will be stored against. */ BaseTexture.addToCache = function addToCache (baseTexture, id) { if (id) { if (baseTexture.textureCacheIds.indexOf(id) === -1) { baseTexture.textureCacheIds.push(id); } if (utils.BaseTextureCache[id]) { // eslint-disable-next-line no-console console.warn(("BaseTexture added to the cache with an id [" + id + "] that already had an entry")); } utils.BaseTextureCache[id] = baseTexture; } }; /** * Remove a BaseTexture from the global BaseTextureCache. * * @static * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. */ BaseTexture.removeFromCache = function removeFromCache (baseTexture) { if (typeof baseTexture === 'string') { var baseTextureFromCache = utils.BaseTextureCache[baseTexture]; if (baseTextureFromCache) { var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); if (index > -1) { baseTextureFromCache.textureCacheIds.splice(index, 1); } delete utils.BaseTextureCache[baseTexture]; return baseTextureFromCache; } } else if (baseTexture && baseTexture.textureCacheIds) { for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { delete utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; } baseTexture.textureCacheIds.length = 0; return baseTexture; } return null; }; Object.defineProperties( BaseTexture.prototype, prototypeAccessors ); return BaseTexture; }(utils.EventEmitter)); /** * Global number of the texture batch, used by multi-texture renderers * * @static * @member {number} */ BaseTexture._globalBatch = 0; /** * A resource that contains a number of sources. * * @class * @extends PIXI.resources.Resource * @memberof PIXI.resources * @param {number|Array<*>} source - Number of items in array or the collection * of image URLs to use. Can also be resources, image elements, canvas, etc. * @param {object} [options] Options to apply to {@link PIXI.resources.autoDetectResource} * @param {number} [options.width] - Width of the resource * @param {number} [options.height] - Height of the resource */ var ArrayResource = /*@__PURE__*/(function (Resource) { function ArrayResource(source, options) { options = options || {}; var urls; var length = source; if (Array.isArray(source)) { urls = source; length = source.length; } Resource.call(this, options.width, options.height); /** * Collection of resources. * @member {Array} * @readonly */ this.items = []; /** * Dirty IDs for each part * @member {Array} * @readonly */ this.itemDirtyIds = []; for (var i = 0; i < length; i++) { var partTexture = new BaseTexture(); this.items.push(partTexture); this.itemDirtyIds.push(-1); } /** * Number of elements in array * * @member {number} * @readonly */ this.length = length; /** * Promise when loading * @member {Promise} * @private * @default null */ this._load = null; if (urls) { for (var i$1 = 0; i$1 < length; i$1++) { this.addResourceAt(autoDetectResource(urls[i$1], options), i$1); } } } if ( Resource ) ArrayResource.__proto__ = Resource; ArrayResource.prototype = Object.create( Resource && Resource.prototype ); ArrayResource.prototype.constructor = ArrayResource; /** * Destroy this BaseImageResource * @override */ ArrayResource.prototype.dispose = function dispose () { for (var i = 0, len = this.length; i < len; i++) { this.items[i].destroy(); } this.items = null; this.itemDirtyIds = null; this._load = null; }; /** * Set a resource by ID * * @param {PIXI.resources.Resource} resource * @param {number} index - Zero-based index of resource to set * @return {PIXI.resources.ArrayResource} Instance for chaining */ ArrayResource.prototype.addResourceAt = function addResourceAt (resource, index) { var baseTexture = this.items[index]; if (!baseTexture) { throw new Error(("Index " + index + " is out of bounds")); } // Inherit the first resource dimensions if (resource.valid && !this.valid) { this.resize(resource.width, resource.height); } this.items[index].setResource(resource); return this; }; /** * Set the parent base texture * @member {PIXI.BaseTexture} * @override */ ArrayResource.prototype.bind = function bind (baseTexture) { Resource.prototype.bind.call(this, baseTexture); baseTexture.target = constants.TARGETS.TEXTURE_2D_ARRAY; for (var i = 0; i < this.length; i++) { this.items[i].on('update', baseTexture.update, baseTexture); } }; /** * Unset the parent base texture * @member {PIXI.BaseTexture} * @override */ ArrayResource.prototype.unbind = function unbind (baseTexture) { Resource.prototype.unbind.call(this, baseTexture); for (var i = 0; i < this.length; i++) { this.items[i].off('update', baseTexture.update, baseTexture); } }; /** * Load all the resources simultaneously * @override * @return {Promise} When load is resolved */ ArrayResource.prototype.load = function load () { var this$1 = this; if (this._load) { return this._load; } var resources = this.items.map(function (item) { return item.resource; }); // TODO: also implement load part-by-part strategy var promises = resources.map(function (item) { return item.load(); }); this._load = Promise.all(promises) .then(function () { var ref = resources[0]; var width = ref.width; var height = ref.height; this$1.resize(width, height); return Promise.resolve(this$1); } ); return this._load; }; /** * Upload the resources to the GPU. * @param {PIXI.Renderer} renderer * @param {PIXI.BaseTexture} texture * @param {PIXI.GLTexture} glTexture * @returns {boolean} whether texture was uploaded */ ArrayResource.prototype.upload = function upload (renderer, texture, glTexture) { var ref = this; var length = ref.length; var itemDirtyIds = ref.itemDirtyIds; var items = ref.items; var gl = renderer.gl; if (glTexture.dirtyId < 0) { gl.texImage3D( gl.TEXTURE_2D_ARRAY, 0, texture.format, this._width, this._height, length, 0, texture.format, texture.type, null ); } for (var i = 0; i < length; i++) { var item = items[i]; if (itemDirtyIds[i] < item.dirtyId) { itemDirtyIds[i] = item.dirtyId; if (item.valid) { gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, // xoffset 0, // yoffset i, // zoffset item.resource.width, item.resource.height, 1, texture.format, texture.type, item.resource.source ); } } } return true; }; return ArrayResource; }(Resource)); /** * @interface OffscreenCanvas */ /** * Resource type for HTMLCanvasElement. * @class * @extends PIXI.resources.BaseImageResource * @memberof PIXI.resources * @param {HTMLCanvasElement} source - Canvas element to use */ var CanvasResource = /*@__PURE__*/(function (BaseImageResource) { function CanvasResource () { BaseImageResource.apply(this, arguments); } if ( BaseImageResource ) CanvasResource.__proto__ = BaseImageResource; CanvasResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype ); CanvasResource.prototype.constructor = CanvasResource; CanvasResource.test = function test (source) { var OffscreenCanvas = window.OffscreenCanvas; // Check for browsers that don't yet support OffscreenCanvas if (OffscreenCanvas && source instanceof OffscreenCanvas) { return true; } return source instanceof HTMLCanvasElement; }; return CanvasResource; }(BaseImageResource)); /** * Resource for a CubeTexture which contains six resources. * * @class * @extends PIXI.resources.ArrayResource * @memberof PIXI.resources * @param {Array} [source] Collection of URLs or resources * to use as the sides of the cube. * @param {object} [options] - ImageResource options * @param {number} [options.width] - Width of resource * @param {number} [options.height] - Height of resource */ var CubeResource = /*@__PURE__*/(function (ArrayResource) { function CubeResource(source, options) { options = options || {}; ArrayResource.call(this, source, options); if (this.length !== CubeResource.SIDES) { throw new Error(("Invalid length. Got " + (this.length) + ", expected 6")); } for (var i = 0; i < CubeResource.SIDES; i++) { this.items[i].target = constants.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i; } if (options.autoLoad !== false) { this.load(); } } if ( ArrayResource ) CubeResource.__proto__ = ArrayResource; CubeResource.prototype = Object.create( ArrayResource && ArrayResource.prototype ); CubeResource.prototype.constructor = CubeResource; /** * Add binding * * @override * @param {PIXI.BaseTexture} baseTexture - parent base texture */ CubeResource.prototype.bind = function bind (baseTexture) { ArrayResource.prototype.bind.call(this, baseTexture); baseTexture.target = constants.TARGETS.TEXTURE_CUBE_MAP; }; /** * Upload the resource * * @returns {boolean} true is success */ CubeResource.prototype.upload = function upload (renderer, baseTexture, glTexture) { var dirty = this.itemDirtyIds; for (var i = 0; i < CubeResource.SIDES; i++) { var side = this.items[i]; if (dirty[i] < side.dirtyId) { dirty[i] = side.dirtyId; if (side.valid) { side.resource.upload(renderer, side, glTexture); } } } return true; }; return CubeResource; }(ArrayResource)); /** * Number of texture sides to store for CubeResources * * @name PIXI.resources.CubeResource.SIDES * @static * @member {number} * @default 6 */ CubeResource.SIDES = 6; /** * Resource type for SVG elements and graphics. * @class * @extends PIXI.resources.BaseImageResource * @memberof PIXI.resources * @param {string} source - Base64 encoded SVG element or URL for SVG file. * @param {object} [options] - Options to use * @param {number} [options.scale=1] Scale to apply to SVG. Overridden by... * @param {number} [options.width] Rasterize SVG this wide. Aspect ratio preserved if height not specified. * @param {number} [options.height] Rasterize SVG this high. Aspect ratio preserved if width not specified. * @param {boolean} [options.autoLoad=true] Start loading right away. */ var SVGResource = /*@__PURE__*/(function (BaseImageResource) { function SVGResource(source, options) { options = options || {}; BaseImageResource.call(this, document.createElement('canvas')); this._width = 0; this._height = 0; /** * Base64 encoded SVG element or URL for SVG file * @readonly * @member {string} */ this.svg = source; /** * The source scale to apply when rasterizing on load * @readonly * @member {number} */ this.scale = options.scale || 1; /** * A width override for rasterization on load * @readonly * @member {number} */ this._overrideWidth = options.width; /** * A height override for rasterization on load * @readonly * @member {number} */ this._overrideHeight = options.height; /** * Call when completely loaded * @private * @member {function} */ this._resolve = null; /** * Cross origin value to use * @private * @member {boolean|string} */ this._crossorigin = options.crossorigin; /** * Promise when loading * @member {Promise} * @private * @default null */ this._load = null; if (options.autoLoad !== false) { this.load(); } } if ( BaseImageResource ) SVGResource.__proto__ = BaseImageResource; SVGResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype ); SVGResource.prototype.constructor = SVGResource; SVGResource.prototype.load = function load () { var this$1 = this; if (this._load) { return this._load; } this._load = new Promise(function (resolve) { // Save this until after load is finished this$1._resolve = function () { this$1.resize(this$1.source.width, this$1.source.height); resolve(this$1); }; // Convert SVG inline string to data-uri if ((/^\]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len /** * Resource type for HTMLVideoElement. * @class * @extends PIXI.resources.BaseImageResource * @memberof PIXI.resources * @param {HTMLVideoElement|object|string|Array} source - Video element to use. * @param {object} [options] - Options to use * @param {boolean} [options.autoLoad=true] - Start loading the video immediately * @param {boolean} [options.autoPlay=true] - Start playing video immediately * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video. * Leave at 0 to update at every render. * @param {boolean} [options.crossorigin=true] - Load image using cross origin */ var VideoResource = /*@__PURE__*/(function (BaseImageResource) { function VideoResource(source, options) { options = options || {}; if (!(source instanceof HTMLVideoElement)) { var videoElement = document.createElement('video'); // workaround for https://github.com/pixijs/pixi.js/issues/5996 videoElement.setAttribute('preload', 'auto'); videoElement.setAttribute('webkit-playsinline', ''); videoElement.setAttribute('playsinline', ''); if (typeof source === 'string') { source = [source]; } BaseImageResource.crossOrigin(videoElement, (source[0].src || source[0]), options.crossorigin); // array of objects or strings for (var i = 0; i < source.length; ++i) { var sourceElement = document.createElement('source'); var ref = source[i]; var src = ref.src; var mime = ref.mime; src = src || source[i]; var baseSrc = src.split('?').shift().toLowerCase(); var ext = baseSrc.substr(baseSrc.lastIndexOf('.') + 1); mime = mime || ("video/" + ext); sourceElement.src = src; sourceElement.type = mime; videoElement.appendChild(sourceElement); } // Override the source source = videoElement; } BaseImageResource.call(this, source); this.noSubImage = true; this._autoUpdate = true; this._isAutoUpdating = false; this._updateFPS = options.updateFPS || 0; this._msToNextUpdate = 0; /** * When set to true will automatically play videos used by this texture once * they are loaded. If false, it will not modify the playing state. * * @member {boolean} * @default true */ this.autoPlay = options.autoPlay !== false; /** * Promise when loading * @member {Promise} * @private * @default null */ this._load = null; /** * Callback when completed with load. * @member {function} * @private */ this._resolve = null; // Bind for listeners this._onCanPlay = this._onCanPlay.bind(this); this._onError = this._onError.bind(this); if (options.autoLoad !== false) { this.load(); } } if ( BaseImageResource ) VideoResource.__proto__ = BaseImageResource; VideoResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype ); VideoResource.prototype.constructor = VideoResource; var prototypeAccessors = { autoUpdate: { configurable: true },updateFPS: { configurable: true } }; /** * Trigger updating of the texture * * @param {number} [deltaTime=0] - time delta since last tick */ VideoResource.prototype.update = function update (deltaTime) { if ( deltaTime === void 0 ) deltaTime = 0; if (!this.destroyed) { // account for if video has had its playbackRate changed var elapsedMS = ticker.Ticker.shared.elapsedMS * this.source.playbackRate; this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS); if (!this._updateFPS || this._msToNextUpdate <= 0) { BaseImageResource.prototype.update.call(this, deltaTime); this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0; } } }; /** * Start preloading the video resource. * * @protected * @return {Promise} Handle the validate event */ VideoResource.prototype.load = function load () { var this$1 = this; if (this._load) { return this._load; } var source = this.source; if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { source.complete = true; } source.addEventListener('play', this._onPlayStart.bind(this)); source.addEventListener('pause', this._onPlayStop.bind(this)); if (!this._isSourceReady()) { source.addEventListener('canplay', this._onCanPlay); source.addEventListener('canplaythrough', this._onCanPlay); source.addEventListener('error', this._onError, true); } else { this._onCanPlay(); } this._load = new Promise(function (resolve) { if (this$1.valid) { resolve(this$1); } else { this$1._resolve = resolve; source.load(); } }); return this._load; }; /** * Handle video error events. * * @private */ VideoResource.prototype._onError = function _onError () { this.source.removeEventListener('error', this._onError, true); this.onError.run(event); }; /** * Returns true if the underlying source is playing. * * @private * @return {boolean} True if playing. */ VideoResource.prototype._isSourcePlaying = function _isSourcePlaying () { var source = this.source; return (source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2); }; /** * Returns true if the underlying source is ready for playing. * * @private * @return {boolean} True if ready. */ VideoResource.prototype._isSourceReady = function _isSourceReady () { return this.source.readyState === 3 || this.source.readyState === 4; }; /** * Runs the update loop when the video is ready to play * * @private */ VideoResource.prototype._onPlayStart = function _onPlayStart () { // Just in case the video has not received its can play even yet.. if (!this.valid) { this._onCanPlay(); } if (!this._isAutoUpdating && this.autoUpdate) { ticker.Ticker.shared.add(this.update, this); this._isAutoUpdating = true; } }; /** * Fired when a pause event is triggered, stops the update loop * * @private */ VideoResource.prototype._onPlayStop = function _onPlayStop () { if (this._isAutoUpdating) { ticker.Ticker.shared.remove(this.update, this); this._isAutoUpdating = false; } }; /** * Fired when the video is loaded and ready to play * * @private */ VideoResource.prototype._onCanPlay = function _onCanPlay () { var ref = this; var source = ref.source; source.removeEventListener('canplay', this._onCanPlay); source.removeEventListener('canplaythrough', this._onCanPlay); var valid = this.valid; this.resize(source.videoWidth, source.videoHeight); // prevent multiple loaded dispatches.. if (!valid && this._resolve) { this._resolve(this); this._resolve = null; } if (this._isSourcePlaying()) { this._onPlayStart(); } else if (this.autoPlay) { source.play(); } }; /** * Destroys this texture * @override */ VideoResource.prototype.dispose = function dispose () { if (this._isAutoUpdating) { ticker.Ticker.shared.remove(this.update, this); } if (this.source) { this.source.removeEventListener('error', this._onError, true); this.source.pause(); this.source.src = ''; this.source.load(); } BaseImageResource.prototype.dispose.call(this); }; /** * Should the base texture automatically update itself, set to true by default * * @member {boolean} */ prototypeAccessors.autoUpdate.get = function () { return this._autoUpdate; }; prototypeAccessors.autoUpdate.set = function (value) // eslint-disable-line require-jsdoc { if (value !== this._autoUpdate) { this._autoUpdate = value; if (!this._autoUpdate && this._isAutoUpdating) { ticker.Ticker.shared.remove(this.update, this); this._isAutoUpdating = false; } else if (this._autoUpdate && !this._isAutoUpdating) { ticker.Ticker.shared.add(this.update, this); this._isAutoUpdating = true; } } }; /** * How many times a second to update the texture from the video. Leave at 0 to update at every render. * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient. * * @member {number} */ prototypeAccessors.updateFPS.get = function () { return this._updateFPS; }; prototypeAccessors.updateFPS.set = function (value) // eslint-disable-line require-jsdoc { if (value !== this._updateFPS) { this._updateFPS = value; } }; /** * Used to auto-detect the type of resource. * * @static * @param {*} source - The source object * @param {string} extension - The extension of source, if set * @return {boolean} `true` if video source */ VideoResource.test = function test (source, extension) { return (source instanceof HTMLVideoElement) || VideoResource.TYPES.indexOf(extension) > -1; }; Object.defineProperties( VideoResource.prototype, prototypeAccessors ); return VideoResource; }(BaseImageResource)); /** * List of common video file extensions supported by VideoResource. * @constant * @member {Array} * @static * @readonly */ VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov']; /** * Resource type for ImageBitmap. * @class * @extends PIXI.resources.BaseImageResource * @memberof PIXI.resources * @param {ImageBitmap} source - Image element to use */ var ImageBitmapResource = /*@__PURE__*/(function (BaseImageResource) { function ImageBitmapResource () { BaseImageResource.apply(this, arguments); } if ( BaseImageResource ) ImageBitmapResource.__proto__ = BaseImageResource; ImageBitmapResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype ); ImageBitmapResource.prototype.constructor = ImageBitmapResource; ImageBitmapResource.test = function test (source) { return !!window.createImageBitmap && source instanceof ImageBitmap; }; return ImageBitmapResource; }(BaseImageResource)); INSTALLED.push( ImageResource, ImageBitmapResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource ); var index = ({ INSTALLED: INSTALLED, autoDetectResource: autoDetectResource, ArrayResource: ArrayResource, BufferResource: BufferResource, CanvasResource: CanvasResource, CubeResource: CubeResource, ImageResource: ImageResource, ImageBitmapResource: ImageBitmapResource, SVGResource: SVGResource, VideoResource: VideoResource, Resource: Resource, BaseImageResource: BaseImageResource }); /** * System is a base class used for extending systems used by the {@link PIXI.Renderer} * * @see PIXI.Renderer#addSystem * @class * @memberof PIXI */ var System = function System(renderer) { /** * The renderer this manager works for. * * @member {PIXI.Renderer} */ this.renderer = renderer; }; /** * Generic destroy methods to be overridden by the subclass */ System.prototype.destroy = function destroy () { this.renderer = null; }; /** * Resource type for DepthTexture. * @class * @extends PIXI.resources.BufferResource * @memberof PIXI.resources */ var DepthResource = /*@__PURE__*/(function (BufferResource) { function DepthResource () { BufferResource.apply(this, arguments); } if ( BufferResource ) DepthResource.__proto__ = BufferResource; DepthResource.prototype = Object.create( BufferResource && BufferResource.prototype ); DepthResource.prototype.constructor = DepthResource; DepthResource.prototype.upload = function upload (renderer, baseTexture, glTexture) { var gl = renderer.gl; gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants.ALPHA_MODES.UNPACK); if (glTexture.width === baseTexture.width && glTexture.height === baseTexture.height) { gl.texSubImage2D( baseTexture.target, 0, 0, 0, baseTexture.width, baseTexture.height, baseTexture.format, baseTexture.type, this.data ); } else { glTexture.width = baseTexture.width; glTexture.height = baseTexture.height; gl.texImage2D( baseTexture.target, 0, gl.DEPTH_COMPONENT16, // Needed for depth to render properly in webgl2.0 baseTexture.width, baseTexture.height, 0, baseTexture.format, baseTexture.type, this.data ); } return true; }; return DepthResource; }(BufferResource)); /** * Frame buffer used by the BaseRenderTexture * * @class * @memberof PIXI */ var Framebuffer = function Framebuffer(width, height) { this.width = Math.ceil(width || 100); this.height = Math.ceil(height || 100); this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; this.dirtySize = 0; this.depthTexture = null; this.colorTextures = []; this.glFramebuffers = {}; this.disposeRunner = new runner.Runner('disposeFramebuffer', 2); }; var prototypeAccessors$1 = { colorTexture: { configurable: true } }; /** * Reference to the colorTexture. * * @member {PIXI.Texture[]} * @readonly */ prototypeAccessors$1.colorTexture.get = function () { return this.colorTextures[0]; }; /** * Add texture to the colorTexture array * * @param {number} [index=0] - Index of the array to add the texture to * @param {PIXI.Texture} [texture] - Texture to add to the array */ Framebuffer.prototype.addColorTexture = function addColorTexture (index, texture) { if ( index === void 0 ) index = 0; // TODO add some validation to the texture - same width / height etc? this.colorTextures[index] = texture || new BaseTexture(null, { scaleMode: 0, resolution: 1, mipmap: false, width: this.width, height: this.height }); this.dirtyId++; this.dirtyFormat++; return this; }; /** * Add a depth texture to the frame buffer * * @param {PIXI.Texture} [texture] - Texture to add */ Framebuffer.prototype.addDepthTexture = function addDepthTexture (texture) { /* eslint-disable max-len */ this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), { scaleMode: 0, resolution: 1, width: this.width, height: this.height, mipmap: false, format: constants.FORMATS.DEPTH_COMPONENT, type: constants.TYPES.UNSIGNED_SHORT }); /* eslint-disable max-len */ this.dirtyId++; this.dirtyFormat++; return this; }; /** * Enable depth on the frame buffer */ Framebuffer.prototype.enableDepth = function enableDepth () { this.depth = true; this.dirtyId++; this.dirtyFormat++; return this; }; /** * Enable stencil on the frame buffer */ Framebuffer.prototype.enableStencil = function enableStencil () { this.stencil = true; this.dirtyId++; this.dirtyFormat++; return this; }; /** * Resize the frame buffer * * @param {number} width - Width of the frame buffer to resize to * @param {number} height - Height of the frame buffer to resize to */ Framebuffer.prototype.resize = function resize (width, height) { width = Math.ceil(width); height = Math.ceil(height); if (width === this.width && height === this.height) { return; } this.width = width; this.height = height; this.dirtyId++; this.dirtySize++; for (var i = 0; i < this.colorTextures.length; i++) { var texture = this.colorTextures[i]; var resolution = texture.resolution; // take into acount the fact the texture may have a different resolution.. texture.setSize(width / resolution, height / resolution); } if (this.depthTexture) { var resolution$1 = this.depthTexture.resolution; this.depthTexture.setSize(width / resolution$1, height / resolution$1); } }; /** * disposes WebGL resources that are connected to this geometry */ Framebuffer.prototype.dispose = function dispose () { this.disposeRunner.run(this, false); }; Object.defineProperties( Framebuffer.prototype, prototypeAccessors$1 ); /** * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. * * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded * otherwise black rectangles will be drawn instead. * * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position * and rotation of the given Display Objects is ignored. For example: * * ```js * let renderer = PIXI.autoDetectRenderer(); * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 }); * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); * let sprite = PIXI.Sprite.from("spinObj_01.png"); * * sprite.position.x = 800/2; * sprite.position.y = 600/2; * sprite.anchor.x = 0.5; * sprite.anchor.y = 0.5; * * renderer.render(sprite, renderTexture); * ``` * * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 * you can clear the transform * * ```js * * sprite.setTransform() * * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 }); * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); * * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture * ``` * * @class * @extends PIXI.BaseTexture * @memberof PIXI */ var BaseRenderTexture = /*@__PURE__*/(function (BaseTexture) { function BaseRenderTexture(options) { if (typeof options === 'number') { /* eslint-disable prefer-rest-params */ // Backward compatibility of signature var width$1 = arguments[0]; var height$1 = arguments[1]; var scaleMode = arguments[2]; var resolution = arguments[3]; options = { width: width$1, height: height$1, scaleMode: scaleMode, resolution: resolution }; /* eslint-enable prefer-rest-params */ } BaseTexture.call(this, null, options); var ref = options || {}; var width = ref.width; var height = ref.height; // Set defaults this.mipmap = false; this.width = Math.ceil(width) || 100; this.height = Math.ceil(height) || 100; this.valid = true; /** * A reference to the canvas render target (we only need one as this can be shared across renderers) * * @protected * @member {object} */ this._canvasRenderTarget = null; this.clearColor = [0, 0, 0, 0]; this.framebuffer = new Framebuffer(this.width * this.resolution, this.height * this.resolution) .addColorTexture(0, this); // TODO - could this be added the systems? /** * The data structure for the stencil masks. * * @member {PIXI.MaskData[]} */ this.maskStack = []; /** * The data structure for the filters. * * @member {Object[]} */ this.filterStack = [{}]; } if ( BaseTexture ) BaseRenderTexture.__proto__ = BaseTexture; BaseRenderTexture.prototype = Object.create( BaseTexture && BaseTexture.prototype ); BaseRenderTexture.prototype.constructor = BaseRenderTexture; /** * Resizes the BaseRenderTexture. * * @param {number} width - The width to resize to. * @param {number} height - The height to resize to. */ BaseRenderTexture.prototype.resize = function resize (width, height) { width = Math.ceil(width); height = Math.ceil(height); this.framebuffer.resize(width * this.resolution, height * this.resolution); }; /** * Frees the texture and framebuffer from WebGL memory without destroying this texture object. * This means you can still use the texture later which will upload it to GPU * memory again. * * @fires PIXI.BaseTexture#dispose */ BaseRenderTexture.prototype.dispose = function dispose () { this.framebuffer.dispose(); BaseTexture.prototype.dispose.call(this); }; /** * Destroys this texture. * */ BaseRenderTexture.prototype.destroy = function destroy () { BaseTexture.prototype.destroy.call(this, true); this.framebuffer = null; }; return BaseRenderTexture; }(BaseTexture)); /** * Stores a texture's frame in UV coordinates, in * which everything lies in the rectangle `[(0,0), (1,0), * (1,1), (0,1)]`. * * | Corner | Coordinates | * |--------------|-------------| * | Top-Left | `(x0,y0)` | * | Top-Right | `(x1,y1)` | * | Bottom-Right | `(x2,y2)` | * | Bottom-Left | `(x3,y3)` | * * @class * @protected * @memberof PIXI */ var TextureUvs = function TextureUvs() { /** * X-component of top-left corner `(x0,y0)`. * * @member {number} */ this.x0 = 0; /** * Y-component of top-left corner `(x0,y0)`. * * @member {number} */ this.y0 = 0; /** * X-component of top-right corner `(x1,y1)`. * * @member {number} */ this.x1 = 1; /** * Y-component of top-right corner `(x1,y1)`. * * @member {number} */ this.y1 = 0; /** * X-component of bottom-right corner `(x2,y2)`. * * @member {number} */ this.x2 = 1; /** * Y-component of bottom-right corner `(x2,y2)`. * * @member {number} */ this.y2 = 1; /** * X-component of bottom-left corner `(x3,y3)`. * * @member {number} */ this.x3 = 0; /** * Y-component of bottom-right corner `(x3,y3)`. * * @member {number} */ this.y3 = 1; this.uvsFloat32 = new Float32Array(8); }; /** * Sets the texture Uvs based on the given frame information. * * @protected * @param {PIXI.Rectangle} frame - The frame of the texture * @param {PIXI.Rectangle} baseFrame - The base frame of the texture * @param {number} rotate - Rotation of frame, see {@link PIXI.groupD8} */ TextureUvs.prototype.set = function set (frame, baseFrame, rotate) { var tw = baseFrame.width; var th = baseFrame.height; if (rotate) { // width and height div 2 div baseFrame size var w2 = frame.width / 2 / tw; var h2 = frame.height / 2 / th; // coordinates of center var cX = (frame.x / tw) + w2; var cY = (frame.y / th) + h2; rotate = math.groupD8.add(rotate, math.groupD8.NW); // NW is top-left corner this.x0 = cX + (w2 * math.groupD8.uX(rotate)); this.y0 = cY + (h2 * math.groupD8.uY(rotate)); rotate = math.groupD8.add(rotate, 2); // rotate 90 degrees clockwise this.x1 = cX + (w2 * math.groupD8.uX(rotate)); this.y1 = cY + (h2 * math.groupD8.uY(rotate)); rotate = math.groupD8.add(rotate, 2); this.x2 = cX + (w2 * math.groupD8.uX(rotate)); this.y2 = cY + (h2 * math.groupD8.uY(rotate)); rotate = math.groupD8.add(rotate, 2); this.x3 = cX + (w2 * math.groupD8.uX(rotate)); this.y3 = cY + (h2 * math.groupD8.uY(rotate)); } else { this.x0 = frame.x / tw; this.y0 = frame.y / th; this.x1 = (frame.x + frame.width) / tw; this.y1 = frame.y / th; this.x2 = (frame.x + frame.width) / tw; this.y2 = (frame.y + frame.height) / th; this.x3 = frame.x / tw; this.y3 = (frame.y + frame.height) / th; } this.uvsFloat32[0] = this.x0; this.uvsFloat32[1] = this.y0; this.uvsFloat32[2] = this.x1; this.uvsFloat32[3] = this.y1; this.uvsFloat32[4] = this.x2; this.uvsFloat32[5] = this.y2; this.uvsFloat32[6] = this.x3; this.uvsFloat32[7] = this.y3; }; var DEFAULT_UVS = new TextureUvs(); /** * A texture stores the information that represents an image or part of an image. * * It cannot be added to the display list directly; instead use it as the texture for a Sprite. * If no frame is provided for a texture, then the whole image is used. * * You can directly create a texture from an image and then reuse it multiple times like this : * * ```js * let texture = PIXI.Texture.from('assets/image.png'); * let sprite1 = new PIXI.Sprite(texture); * let sprite2 = new PIXI.Sprite(texture); * ``` * * If you didnt pass the texture frame to constructor, it enables `noFrame` mode: * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture. * * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. * You can check for this by checking the sprite's _textureID property. * ```js * var texture = PIXI.Texture.from('assets/image.svg'); * var sprite1 = new PIXI.Sprite(texture); * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file * ``` * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. * * @class * @extends PIXI.utils.EventEmitter * @memberof PIXI */ var Texture = /*@__PURE__*/(function (EventEmitter) { function Texture(baseTexture, frame, orig, trim, rotate, anchor) { EventEmitter.call(this); /** * Does this Texture have any frame data assigned to it? * * This mode is enabled automatically if no frame was passed inside constructor. * * In this mode texture is subscribed to baseTexture events, and fires `update` on any change. * * Beware, after loading or resize of baseTexture event can fired two times! * If you want more control, subscribe on baseTexture itself. * * ```js * texture.on('update', () => {}); * ``` * * Any assignment of `frame` switches off `noFrame` mode. * * @member {boolean} */ this.noFrame = false; if (!frame) { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } if (baseTexture instanceof Texture) { baseTexture = baseTexture.baseTexture; } /** * The base texture that this texture uses. * * @member {PIXI.BaseTexture} */ this.baseTexture = baseTexture; /** * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) * * @member {PIXI.Rectangle} */ this._frame = frame; /** * This is the trimmed area of original texture, before it was put in atlas * Please call `updateUvs()` after you change coordinates of `trim` manually. * * @member {PIXI.Rectangle} */ this.trim = trim; /** * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. * * @member {boolean} */ this.valid = false; /** * This will let a renderer know that a texture has been updated (used mainly for WebGL uv updates) * * @member {boolean} */ this.requiresUpdate = false; /** * The WebGL UV data cache. Can be used as quad UV * * @member {PIXI.TextureUvs} * @protected */ this._uvs = DEFAULT_UVS; /** * Default TextureMatrix instance for this texture * By default that object is not created because its heavy * * @member {PIXI.TextureMatrix} */ this.uvMatrix = null; /** * This is the area of original texture, before it was put in atlas * * @member {PIXI.Rectangle} */ this.orig = orig || frame;// new Rectangle(0, 0, 1, 1); this._rotate = Number(rotate || 0); if (rotate === true) { // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures this._rotate = 2; } else if (this._rotate % 2 !== 0) { throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); } /** * Anchor point that is used as default if sprite is created with this texture. * Changing the `defaultAnchor` at a later point of time will not update Sprite's anchor point. * @member {PIXI.Point} * @default {0,0} */ this.defaultAnchor = anchor ? new math.Point(anchor.x, anchor.y) : new math.Point(0, 0); /** * Update ID is observed by sprites and TextureMatrix instances. * Call updateUvs() to increment it. * * @member {number} * @protected */ this._updateID = 0; /** * The ids under which this Texture has been added to the texture cache. This is * automatically set as long as Texture.addToCache is used, but may not be set if a * Texture is added directly to the TextureCache array. * * @member {string[]} */ this.textureCacheIds = []; if (!baseTexture.valid) { baseTexture.once('loaded', this.onBaseTextureUpdated, this); } else if (this.noFrame) { // if there is no frame we should monitor for any base texture changes.. if (baseTexture.valid) { this.onBaseTextureUpdated(baseTexture); } } else { this.frame = frame; } if (this.noFrame) { baseTexture.on('update', this.onBaseTextureUpdated, this); } } if ( EventEmitter ) Texture.__proto__ = EventEmitter; Texture.prototype = Object.create( EventEmitter && EventEmitter.prototype ); Texture.prototype.constructor = Texture; var prototypeAccessors = { resolution: { configurable: true },frame: { configurable: true },rotate: { configurable: true },width: { configurable: true },height: { configurable: true } }; /** * Updates this texture on the gpu. * * Calls the TextureResource update. * * If you adjusted `frame` manually, please call `updateUvs()` instead. * */ Texture.prototype.update = function update () { if (this.baseTexture.resource) { this.baseTexture.resource.update(); } }; /** * Called when the base texture is updated * * @protected * @param {PIXI.BaseTexture} baseTexture - The base texture. */ Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated (baseTexture) { if (this.noFrame) { if (!this.baseTexture.valid) { return; } this._frame.width = baseTexture.width; this._frame.height = baseTexture.height; this.valid = true; this.updateUvs(); } else { // TODO this code looks confusing.. boo to abusing getters and setters! // if user gave us frame that has bigger size than resized texture it can be a problem this.frame = this._frame; } this.emit('update', this); }; /** * Destroys this texture * * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well */ Texture.prototype.destroy = function destroy (destroyBase) { if (this.baseTexture) { if (destroyBase) { var ref = this.baseTexture; var resource = ref.resource; // delete the texture if it exists in the texture cache.. // this only needs to be removed if the base texture is actually destroyed too.. if (resource && utils.TextureCache[resource.url]) { Texture.removeFromCache(resource.url); } this.baseTexture.destroy(); } this.baseTexture.off('update', this.onBaseTextureUpdated, this); this.baseTexture = null; } this._frame = null; this._uvs = null; this.trim = null; this.orig = null; this.valid = false; Texture.removeFromCache(this); this.textureCacheIds = null; }; /** * Creates a new texture object that acts the same as this one. * * @return {PIXI.Texture} The new texture */ Texture.prototype.clone = function clone () { return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate, this.defaultAnchor); }; /** * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. * Call it after changing the frame */ Texture.prototype.updateUvs = function updateUvs () { if (this._uvs === DEFAULT_UVS) { this._uvs = new TextureUvs(); } this._uvs.set(this._frame, this.baseTexture, this.rotate); this._updateID++; }; /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * * @static * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source * Source to create texture from * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. * @param {boolean} [strict] Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. * @return {PIXI.Texture} The newly created texture */ Texture.from = function from (source, options, strict) { if ( options === void 0 ) options = {}; if ( strict === void 0 ) strict = settings.settings.STRICT_TEXTURE_CACHE; var isFrame = typeof source === 'string'; var cacheId = null; if (isFrame) { cacheId = source; } else { if (!source._pixiId) { source._pixiId = "pixiid_" + (utils.uid()); } cacheId = source._pixiId; } var texture = utils.TextureCache[cacheId]; // Strict-mode rejects invalid cacheIds if (isFrame && strict && !texture) { throw new Error(("The cacheId \"" + cacheId + "\" does not exist in TextureCache.")); } if (!texture) { if (!options.resolution) { options.resolution = utils.getResolutionOfUrl(source); } texture = new Texture(new BaseTexture(source, options)); texture.baseTexture.cacheId = cacheId; BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } // lets assume its a base texture! return texture; }; /** * Create a new Texture with a BufferResource from a Float32Array. * RGBA values are floats from 0 to 1. * @static * @param {Float32Array|Uint8Array} buffer The optional array to use, if no data * is provided, a new Float32Array is created. * @param {number} width - Width of the resource * @param {number} height - Height of the resource * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. * @return {PIXI.Texture} The resulting new BaseTexture */ Texture.fromBuffer = function fromBuffer (buffer, width, height, options) { return new Texture(BaseTexture.fromBuffer(buffer, width, height, options)); }; /** * Create a texture from a source and add to the cache. * * @static * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. * @param {String} imageUrl - File name of texture, for cache and resolving resolution. * @param {String} [name] - Human readable name for the texture cache. If no name is * specified, only `imageUrl` will be used as the cache ID. * @return {PIXI.Texture} Output texture */ Texture.fromLoader = function fromLoader (source, imageUrl, name) { var resource = new ImageResource(source); resource.url = imageUrl; var baseTexture = new BaseTexture(resource, { scaleMode: settings.settings.SCALE_MODE, resolution: utils.getResolutionOfUrl(imageUrl), }); var texture = new Texture(baseTexture); // No name, use imageUrl instead if (!name) { name = imageUrl; } // lets also add the frame to pixi's global cache for 'fromLoader' function BaseTexture.addToCache(texture.baseTexture, name); Texture.addToCache(texture, name); // also add references by url if they are different. if (name !== imageUrl) { BaseTexture.addToCache(texture.baseTexture, imageUrl); Texture.addToCache(texture, imageUrl); } return texture; }; /** * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. * * @static * @param {PIXI.Texture} texture - The Texture to add to the cache. * @param {string} id - The id that the Texture will be stored against. */ Texture.addToCache = function addToCache (texture, id) { if (id) { if (texture.textureCacheIds.indexOf(id) === -1) { texture.textureCacheIds.push(id); } if (utils.TextureCache[id]) { // eslint-disable-next-line no-console console.warn(("Texture added to the cache with an id [" + id + "] that already had an entry")); } utils.TextureCache[id] = texture; } }; /** * Remove a Texture from the global TextureCache. * * @static * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself * @return {PIXI.Texture|null} The Texture that was removed */ Texture.removeFromCache = function removeFromCache (texture) { if (typeof texture === 'string') { var textureFromCache = utils.TextureCache[texture]; if (textureFromCache) { var index = textureFromCache.textureCacheIds.indexOf(texture); if (index > -1) { textureFromCache.textureCacheIds.splice(index, 1); } delete utils.TextureCache[texture]; return textureFromCache; } } else if (texture && texture.textureCacheIds) { for (var i = 0; i < texture.textureCacheIds.length; ++i) { // Check that texture matches the one being passed in before deleting it from the cache. if (utils.TextureCache[texture.textureCacheIds[i]] === texture) { delete utils.TextureCache[texture.textureCacheIds[i]]; } } texture.textureCacheIds.length = 0; return texture; } return null; }; /** * Returns resolution of baseTexture * * @member {number} * @readonly */ prototypeAccessors.resolution.get = function () { return this.baseTexture.resolution; }; /** * The frame specifies the region of the base texture that this texture uses. * Please call `updateUvs()` after you change coordinates of `frame` manually. * * @member {PIXI.Rectangle} */ prototypeAccessors.frame.get = function () { return this._frame; }; prototypeAccessors.frame.set = function (frame) // eslint-disable-line require-jsdoc { this._frame = frame; this.noFrame = false; var x = frame.x; var y = frame.y; var width = frame.width; var height = frame.height; var xNotFit = x + width > this.baseTexture.width; var yNotFit = y + height > this.baseTexture.height; if (xNotFit || yNotFit) { var relationship = xNotFit && yNotFit ? 'and' : 'or'; var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + (this.baseTexture.width); var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + (this.baseTexture.height); throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + errorX + " " + relationship + " " + errorY); } this.valid = width && height && this.baseTexture.valid; if (!this.trim && !this.rotate) { this.orig = frame; } if (this.valid) { this.updateUvs(); } }; /** * Indicates whether the texture is rotated inside the atlas * set to 2 to compensate for texture packer rotation * set to 6 to compensate for spine packer rotation * can be used to rotate or mirror sprites * See {@link PIXI.groupD8} for explanation * * @member {number} */ prototypeAccessors.rotate.get = function () { return this._rotate; }; prototypeAccessors.rotate.set = function (rotate) // eslint-disable-line require-jsdoc { this._rotate = rotate; if (this.valid) { this.updateUvs(); } }; /** * The width of the Texture in pixels. * * @member {number} */ prototypeAccessors.width.get = function () { return this.orig.width; }; /** * The height of the Texture in pixels. * * @member {number} */ prototypeAccessors.height.get = function () { return this.orig.height; }; Object.defineProperties( Texture.prototype, prototypeAccessors ); return Texture; }(utils.EventEmitter)); function createWhiteTexture() { var canvas = document.createElement('canvas'); canvas.width = 16; canvas.height = 16; var context = canvas.getContext('2d'); context.fillStyle = 'white'; context.fillRect(0, 0, 16, 16); return new Texture(new BaseTexture(new CanvasResource(canvas))); } function removeAllHandlers(tex) { tex.destroy = function _emptyDestroy() { /* empty */ }; tex.on = function _emptyOn() { /* empty */ }; tex.once = function _emptyOnce() { /* empty */ }; tex.emit = function _emptyEmit() { /* empty */ }; } /** * An empty texture, used often to not have to create multiple empty textures. * Can not be destroyed. * * @static * @constant * @member {PIXI.Texture} */ Texture.EMPTY = new Texture(new BaseTexture()); removeAllHandlers(Texture.EMPTY); removeAllHandlers(Texture.EMPTY.baseTexture); /** * A white texture of 16x16 size, used for graphics and other things * Can not be destroyed. * * @static * @constant * @member {PIXI.Texture} */ Texture.WHITE = createWhiteTexture(); removeAllHandlers(Texture.WHITE); removeAllHandlers(Texture.WHITE.baseTexture); /** * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. * * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded * otherwise black rectangles will be drawn instead. * * __Hint-2__: The actual memory allocation will happen on first render. * You shouldn't create renderTextures each frame just to delete them after, try to reuse them. * * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: * * ```js * let renderer = PIXI.autoDetectRenderer(); * let renderTexture = PIXI.RenderTexture.create(800, 600); * let sprite = PIXI.Sprite.from("spinObj_01.png"); * * sprite.position.x = 800/2; * sprite.position.y = 600/2; * sprite.anchor.x = 0.5; * sprite.anchor.y = 0.5; * * renderer.render(sprite, renderTexture); * ``` * * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 * you can clear the transform * * ```js * * sprite.setTransform() * * let renderTexture = new PIXI.RenderTexture.create(100, 100); * * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture * ``` * * @class * @extends PIXI.Texture * @memberof PIXI */ var RenderTexture = /*@__PURE__*/(function (Texture) { function RenderTexture(baseRenderTexture, frame) { // support for legacy.. var _legacyRenderer = null; if (!(baseRenderTexture instanceof BaseRenderTexture)) { /* eslint-disable prefer-rest-params, no-console */ var width = arguments[1]; var height = arguments[2]; var scaleMode = arguments[3]; var resolution = arguments[4]; // we have an old render texture.. console.warn(("Please use RenderTexture.create(" + width + ", " + height + ") instead of the ctor directly.")); _legacyRenderer = arguments[0]; /* eslint-enable prefer-rest-params, no-console */ frame = null; baseRenderTexture = new BaseRenderTexture({ width: width, height: height, scaleMode: scaleMode, resolution: resolution, }); } /** * The base texture object that this texture uses * * @member {PIXI.BaseTexture} */ Texture.call(this, baseRenderTexture, frame); this.legacyRenderer = _legacyRenderer; /** * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. * * @member {boolean} */ this.valid = true; /** * Stores `sourceFrame` when this texture is inside current filter stack. * You can read it inside filters. * * @readonly * @member {PIXI.Rectangle} */ this.filterFrame = null; /** * The key for pooled texture of FilterSystem * @protected * @member {string} */ this.filterPoolKey = null; this.updateUvs(); } if ( Texture ) RenderTexture.__proto__ = Texture; RenderTexture.prototype = Object.create( Texture && Texture.prototype ); RenderTexture.prototype.constructor = RenderTexture; /** * Resizes the RenderTexture. * * @param {number} width - The width to resize to. * @param {number} height - The height to resize to. * @param {boolean} [resizeBaseTexture=true] - Should the baseTexture.width and height values be resized as well? */ RenderTexture.prototype.resize = function resize (width, height, resizeBaseTexture) { if ( resizeBaseTexture === void 0 ) resizeBaseTexture = true; width = Math.ceil(width); height = Math.ceil(height); // TODO - could be not required.. this.valid = (width > 0 && height > 0); this._frame.width = this.orig.width = width; this._frame.height = this.orig.height = height; if (resizeBaseTexture) { this.baseTexture.resize(width, height); } this.updateUvs(); }; /** * Changes the resolution of baseTexture, but does not change framebuffer size. * * @param {number} resolution - The new resolution to apply to RenderTexture */ RenderTexture.prototype.setResolution = function setResolution (resolution) { var ref = this; var baseTexture = ref.baseTexture; if (baseTexture.resolution === resolution) { return; } baseTexture.setResolution(resolution); this.resize(baseTexture.width, baseTexture.height, false); }; /** * A short hand way of creating a render texture. * * @param {object} [options] - Options * @param {number} [options.width=100] - The width of the render texture * @param {number} [options.height=100] - The height of the render texture * @param {number} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the texture being generated * @return {PIXI.RenderTexture} The new render texture */ RenderTexture.create = function create (options) { // fallback, old-style: create(width, height, scaleMode, resolution) if (typeof options === 'number') { /* eslint-disable prefer-rest-params */ options = { width: options, height: arguments[1], scaleMode: arguments[2], resolution: arguments[3], }; /* eslint-enable prefer-rest-params */ } return new RenderTexture(new BaseRenderTexture(options)); }; return RenderTexture; }(Texture)); /** * Experimental! * * Texture pool, used by FilterSystem and plugins * Stores collection of temporary pow2 or screen-sized renderTextures * * If you use custom RenderTexturePool for your filters, you can use methods * `getFilterTexture` and `returnFilterTexture` same as in * * @class * @memberof PIXI */ var RenderTexturePool = function RenderTexturePool(textureOptions) { this.texturePool = {}; this.textureOptions = textureOptions || {}; /** * Allow renderTextures of the same size as screen, not just pow2 * * Automatically sets to true after `setScreenSize` * * @member {boolean} * @default false */ this.enableFullScreen = false; this._pixelsWidth = 0; this._pixelsHeight = 0; }; /** * creates of texture with params that were specified in pool constructor * * @param {number} realWidth width of texture in pixels * @param {number} realHeight height of texture in pixels * @returns {RenderTexture} */ RenderTexturePool.prototype.createTexture = function createTexture (realWidth, realHeight) { var baseRenderTexture = new BaseRenderTexture(Object.assign({ width: realWidth, height: realHeight, resolution: 1, }, this.textureOptions)); return new RenderTexture(baseRenderTexture); }; /** * Gets a Power-of-Two render texture or fullScreen texture * * @protected * @param {number} minWidth - The minimum width of the render texture in real pixels. * @param {number} minHeight - The minimum height of the render texture in real pixels. * @param {number} [resolution=1] - The resolution of the render texture. * @return {PIXI.RenderTexture} The new render texture. */ RenderTexturePool.prototype.getOptimalTexture = function getOptimalTexture (minWidth, minHeight, resolution) { if ( resolution === void 0 ) resolution = 1; var key = RenderTexturePool.SCREEN_KEY; minWidth *= resolution; minHeight *= resolution; if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) { minWidth = utils.nextPow2(minWidth); minHeight = utils.nextPow2(minHeight); key = ((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF); } if (!this.texturePool[key]) { this.texturePool[key] = []; } var renderTexture = this.texturePool[key].pop(); if (!renderTexture) { renderTexture = this.createTexture(minWidth, minHeight); } renderTexture.filterPoolKey = key; renderTexture.setResolution(resolution); return renderTexture; }; /** * Gets extra texture of the same size as input renderTexture * * `getFilterTexture(input, 0.5)` or `getFilterTexture(0.5, input)` * * @param {PIXI.RenderTexture} input renderTexture from which size and resolution will be copied * @param {number} [resolution] override resolution of the renderTexture * It overrides, it does not multiply * @returns {PIXI.RenderTexture} */ RenderTexturePool.prototype.getFilterTexture = function getFilterTexture (input, resolution) { var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution); filterTexture.filterFrame = input.filterFrame; return filterTexture; }; /** * Place a render texture back into the pool. * @param {PIXI.RenderTexture} renderTexture - The renderTexture to free */ RenderTexturePool.prototype.returnTexture = function returnTexture (renderTexture) { var key = renderTexture.filterPoolKey; renderTexture.filterFrame = null; this.texturePool[key].push(renderTexture); }; /** * Alias for returnTexture, to be compliant with FilterSystem interface * @param {PIXI.RenderTexture} renderTexture - The renderTexture to free */ RenderTexturePool.prototype.returnFilterTexture = function returnFilterTexture (renderTexture) { this.returnTexture(renderTexture); }; /** * Clears the pool * * @param {boolean} [destroyTextures=true] destroy all stored textures */ RenderTexturePool.prototype.clear = function clear (destroyTextures) { destroyTextures = destroyTextures !== false; if (destroyTextures) { for (var i in this.texturePool) { var textures = this.texturePool[i]; if (textures) { for (var j = 0; j < textures.length; j++) { textures[j].destroy(true); } } } } this.texturePool = {}; }; /** * If screen size was changed, drops all screen-sized textures, * sets new screen size, sets `enableFullScreen` to true * * Size is measured in pixels, `renderer.view` can be passed here, not `renderer.screen` * * @param {PIXI.ISize} size - Initial size of screen */ RenderTexturePool.prototype.setScreenSize = function setScreenSize (size) { if (size.width === this._pixelsWidth && size.height === this._pixelsHeight) { return; } var screenKey = RenderTexturePool.SCREEN_KEY; var textures = this.texturePool[screenKey]; this.enableFullScreen = size.width > 0 && size.height > 0; if (textures) { for (var j = 0; j < textures.length; j++) { textures[j].destroy(true); } } this.texturePool[screenKey] = []; this._pixelsWidth = size.width; this._pixelsHeight = size.height; }; /** * Key that is used to store fullscreen renderTextures in a pool * * @static * @const {string} */ RenderTexturePool.SCREEN_KEY = 'screen'; /* eslint-disable max-len */ /** * Holds the information for a single attribute structure required to render geometry. * * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer} * This can include anything from positions, uvs, normals, colors etc. * * @class * @memberof PIXI */ var Attribute = function Attribute(buffer, size, normalized, type, stride, start, instance) { if ( normalized === void 0 ) normalized = false; if ( type === void 0 ) type = 5126; this.buffer = buffer; this.size = size; this.normalized = normalized; this.type = type; this.stride = stride; this.start = start; this.instance = instance; }; /** * Destroys the Attribute. */ Attribute.prototype.destroy = function destroy () { this.buffer = null; }; /** * Helper function that creates an Attribute based on the information provided * * @static * @param {string} buffer the id of the buffer that this attribute will look for * @param {Number} [size=0] the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 * @param {Boolean} [normalized=false] should the data be normalized. * @param {Number} [start=0] How far into the array to start reading values (used for interleaving data) * @param {Number} [type=PIXI.TYPES.FLOAT] what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available * @param {Number} [stride=0] How far apart (in floats) the start of each value is. (used for interleaving data) * * @returns {PIXI.Attribute} A new {@link PIXI.Attribute} based on the information provided */ Attribute.from = function from (buffer, size, normalized, type, stride) { return new Attribute(buffer, size, normalized, type, stride); }; var UID = 0; /* eslint-disable max-len */ /** * A wrapper for data so that it can be used and uploaded by WebGL * * @class * @memberof PIXI */ var Buffer = function Buffer(data, _static, index) { if ( _static === void 0 ) _static = true; if ( index === void 0 ) index = false; /** * The data in the buffer, as a typed array * * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} */ this.data = data || new Float32Array(1); /** * A map of renderer IDs to webgl buffer * * @private * @member {object} */ this._glBuffers = {}; this._updateID = 0; this.index = index; this.static = _static; this.id = UID++; this.disposeRunner = new runner.Runner('disposeBuffer', 2); }; // TODO could explore flagging only a partial upload? /** * flags this buffer as requiring an upload to the GPU * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView} [data] the data to update in the buffer. */ Buffer.prototype.update = function update (data) { this.data = data || this.data; this._updateID++; }; /** * disposes WebGL resources that are connected to this geometry */ Buffer.prototype.dispose = function dispose () { this.disposeRunner.run(this, false); }; /** * Destroys the buffer */ Buffer.prototype.destroy = function destroy () { this.dispose(); this.data = null; }; /** * Helper function that creates a buffer based on an array or TypedArray * * @static * @param {ArrayBufferView | number[]} data the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array. * @return {PIXI.Buffer} A new Buffer based on the data provided. */ Buffer.from = function from (data) { if (data instanceof Array) { data = new Float32Array(data); } return new Buffer(data); }; function getBufferType(array) { if (array.BYTES_PER_ELEMENT === 4) { if (array instanceof Float32Array) { return 'Float32Array'; } else if (array instanceof Uint32Array) { return 'Uint32Array'; } return 'Int32Array'; } else if (array.BYTES_PER_ELEMENT === 2) { if (array instanceof Uint16Array) { return 'Uint16Array'; } } else if (array.BYTES_PER_ELEMENT === 1) { if (array instanceof Uint8Array) { return 'Uint8Array'; } } // TODO map out the rest of the array elements! return null; } /* eslint-disable object-shorthand */ var map = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array, }; function interleaveTypedArrays(arrays, sizes) { var outSize = 0; var stride = 0; var views = {}; for (var i = 0; i < arrays.length; i++) { stride += sizes[i]; outSize += arrays[i].length; } var buffer = new ArrayBuffer(outSize * 4); var out = null; var littleOffset = 0; for (var i$1 = 0; i$1 < arrays.length; i$1++) { var size = sizes[i$1]; var array = arrays[i$1]; var type = getBufferType(array); if (!views[type]) { views[type] = new map[type](buffer); } out = views[type]; for (var j = 0; j < array.length; j++) { var indexStart = ((j / size | 0) * stride) + littleOffset; var index = j % size; out[indexStart + index] = array[j]; } littleOffset += size; } return new Float32Array(buffer); } var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; var UID$1 = 0; /* eslint-disable object-shorthand */ var map$1 = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array, Uint16Array: Uint16Array, }; /* eslint-disable max-len */ /** * The Geometry represents a model. It consists of two components: * - GeometryStyle - The structure of the model such as the attributes layout * - GeometryData - the data of the model - this consists of buffers. * This can include anything from positions, uvs, normals, colors etc. * * Geometry can be defined without passing in a style or data if required (thats how I prefer!) * * ```js * let geometry = new PIXI.Geometry(); * * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2) * geometry.addIndex([0,1,2,1,3,2]) * * ``` * @class * @memberof PIXI */ var Geometry = function Geometry(buffers, attributes) { if ( buffers === void 0 ) buffers = []; if ( attributes === void 0 ) attributes = {}; this.buffers = buffers; this.indexBuffer = null; this.attributes = attributes; /** * A map of renderer IDs to webgl VAOs * * @protected * @type {object} */ this.glVertexArrayObjects = {}; this.id = UID$1++; this.instanced = false; /** * Number of instances in this geometry, pass it to `GeometrySystem.draw()` * @member {number} * @default 1 */ this.instanceCount = 1; this.disposeRunner = new runner.Runner('disposeGeometry', 2); /** * Count of existing (not destroyed) meshes that reference this geometry * @member {number} */ this.refCount = 0; }; /** * * Adds an attribute to the geometry * * @param {String} id - the name of the attribute (matching up to a shader) * @param {PIXI.Buffer|number[]} [buffer] the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it. * @param {Number} [size=0] the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 * @param {Boolean} [normalized=false] should the data be normalized. * @param {Number} [type=PIXI.TYPES.FLOAT] what type of number is the attribute. Check {PIXI.TYPES} to see the ones available * @param {Number} [stride=0] How far apart (in floats) the start of each value is. (used for interleaving data) * @param {Number} [start=0] How far into the array to start reading values (used for interleaving data) * * @return {PIXI.Geometry} returns self, useful for chaining. */ Geometry.prototype.addAttribute = function addAttribute (id, buffer, size, normalized, type, stride, start, instance) { if ( normalized === void 0 ) normalized = false; if ( instance === void 0 ) instance = false; if (!buffer) { throw new Error('You must pass a buffer when creating an attribute'); } // check if this is a buffer! if (!buffer.data) { // its an array! if (buffer instanceof Array) { buffer = new Float32Array(buffer); } buffer = new Buffer(buffer); } var ids = id.split('|'); if (ids.length > 1) { for (var i = 0; i < ids.length; i++) { this.addAttribute(ids[i], buffer, size, normalized, type); } return this; } var bufferIndex = this.buffers.indexOf(buffer); if (bufferIndex === -1) { this.buffers.push(buffer); bufferIndex = this.buffers.length - 1; } this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance); // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; return this; }; /** * returns the requested attribute * * @param {String} id the name of the attribute required * @return {PIXI.Attribute} the attribute requested. */ Geometry.prototype.getAttribute = function getAttribute (id) { return this.attributes[id]; }; /** * returns the requested buffer * * @param {String} id the name of the buffer required * @return {PIXI.Buffer} the buffer requested. */ Geometry.prototype.getBuffer = function getBuffer (id) { return this.buffers[this.getAttribute(id).buffer]; }; /** * * Adds an index buffer to the geometry * The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer. * * @param {PIXI.Buffer|number[]} [buffer] the buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it. * @return {PIXI.Geometry} returns self, useful for chaining. */ Geometry.prototype.addIndex = function addIndex (buffer) { if (!buffer.data) { // its an array! if (buffer instanceof Array) { buffer = new Uint16Array(buffer); } buffer = new Buffer(buffer); } buffer.index = true; this.indexBuffer = buffer; if (this.buffers.indexOf(buffer) === -1) { this.buffers.push(buffer); } return this; }; /** * returns the index buffer * * @return {PIXI.Buffer} the index buffer. */ Geometry.prototype.getIndex = function getIndex () { return this.indexBuffer; }; /** * this function modifies the structure so that all current attributes become interleaved into a single buffer * This can be useful if your model remains static as it offers a little performance boost * * @return {PIXI.Geometry} returns self, useful for chaining. */ Geometry.prototype.interleave = function interleave () { // a simple check to see if buffers are already interleaved.. if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer)) { return this; } // assume already that no buffers are interleaved var arrays = []; var sizes = []; var interleavedBuffer = new Buffer(); var i; for (i in this.attributes) { var attribute = this.attributes[i]; var buffer = this.buffers[attribute.buffer]; arrays.push(buffer.data); sizes.push((attribute.size * byteSizeMap[attribute.type]) / 4); attribute.buffer = 0; } interleavedBuffer.data = interleaveTypedArrays(arrays, sizes); for (i = 0; i < this.buffers.length; i++) { if (this.buffers[i] !== this.indexBuffer) { this.buffers[i].destroy(); } } this.buffers = [interleavedBuffer]; if (this.indexBuffer) { this.buffers.push(this.indexBuffer); } return this; }; Geometry.prototype.getSize = function getSize () { for (var i in this.attributes) { var attribute = this.attributes[i]; var buffer = this.buffers[attribute.buffer]; return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; }; /** * disposes WebGL resources that are connected to this geometry */ Geometry.prototype.dispose = function dispose () { this.disposeRunner.run(this, false); }; /** * Destroys the geometry. */ Geometry.prototype.destroy = function destroy () { this.dispose(); this.buffers = null; this.indexBuffer = null; this.attributes = null; }; /** * returns a clone of the geometry * * @returns {PIXI.Geometry} a new clone of this geometry */ Geometry.prototype.clone = function clone () { var geometry = new Geometry(); for (var i = 0; i < this.buffers.length; i++) { geometry.buffers[i] = new Buffer(this.buffers[i].data.slice()); } for (var i$1 in this.attributes) { var attrib = this.attributes[i$1]; geometry.attributes[i$1] = new Attribute( attrib.buffer, attrib.size, attrib.normalized, attrib.type, attrib.stride, attrib.start, attrib.instance ); } if (this.indexBuffer) { geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)]; geometry.indexBuffer.index = true; } return geometry; }; /** * merges an array of geometries into a new single one * geometry attribute styles must match for this operation to work * * @param {PIXI.Geometry[]} geometries array of geometries to merge * @returns {PIXI.Geometry} shiny new geometry! */ Geometry.merge = function merge (geometries) { // todo add a geometry check! // also a size check.. cant be too big!] var geometryOut = new Geometry(); var arrays = []; var sizes = []; var offsets = []; var geometry; // pass one.. get sizes.. for (var i = 0; i < geometries.length; i++) { geometry = geometries[i]; for (var j = 0; j < geometry.buffers.length; j++) { sizes[j] = sizes[j] || 0; sizes[j] += geometry.buffers[j].data.length; offsets[j] = 0; } } // build the correct size arrays.. for (var i$1 = 0; i$1 < geometry.buffers.length; i$1++) { // TODO types! arrays[i$1] = new map$1[getBufferType(geometry.buffers[i$1].data)](sizes[i$1]); geometryOut.buffers[i$1] = new Buffer(arrays[i$1]); } // pass to set data.. for (var i$2 = 0; i$2 < geometries.length; i$2++) { geometry = geometries[i$2]; for (var j$1 = 0; j$1 < geometry.buffers.length; j$1++) { arrays[j$1].set(geometry.buffers[j$1].data, offsets[j$1]); offsets[j$1] += geometry.buffers[j$1].data.length; } } geometryOut.attributes = geometry.attributes; if (geometry.indexBuffer) { geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)]; geometryOut.indexBuffer.index = true; var offset = 0; var stride = 0; var offset2 = 0; var bufferIndexToCount = 0; // get a buffer for (var i$3 = 0; i$3 < geometry.buffers.length; i$3++) { if (geometry.buffers[i$3] !== geometry.indexBuffer) { bufferIndexToCount = i$3; break; } } // figure out the stride of one buffer.. for (var i$4 in geometry.attributes) { var attribute = geometry.attributes[i$4]; if ((attribute.buffer | 0) === bufferIndexToCount) { stride += ((attribute.size * byteSizeMap[attribute.type]) / 4); } } // time to off set all indexes.. for (var i$5 = 0; i$5 < geometries.length; i$5++) { var indexBufferData = geometries[i$5].indexBuffer.data; for (var j$2 = 0; j$2 < indexBufferData.length; j$2++) { geometryOut.indexBuffer.data[j$2 + offset2] += offset; } offset += geometry.buffers[bufferIndexToCount].data.length / (stride); offset2 += indexBufferData.length; } } return geometryOut; }; /** * Helper class to create a quad * * @class * @memberof PIXI */ var Quad = /*@__PURE__*/(function (Geometry) { function Quad() { Geometry.call(this); this.addAttribute('aVertexPosition', [ 0, 0, 1, 0, 1, 1, 0, 1 ]) .addIndex([0, 1, 3, 2]); } if ( Geometry ) Quad.__proto__ = Geometry; Quad.prototype = Object.create( Geometry && Geometry.prototype ); Quad.prototype.constructor = Quad; return Quad; }(Geometry)); /** * Helper class to create a quad with uvs like in v4 * * @class * @memberof PIXI * @extends PIXI.Geometry */ var QuadUv = /*@__PURE__*/(function (Geometry) { function QuadUv() { Geometry.call(this); /** * An array of vertices * * @member {Float32Array} */ this.vertices = new Float32Array([ -1, -1, 1, -1, 1, 1, -1, 1 ]); /** * The Uvs of the quad * * @member {Float32Array} */ this.uvs = new Float32Array([ 0, 0, 1, 0, 1, 1, 0, 1 ]); this.vertexBuffer = new Buffer(this.vertices); this.uvBuffer = new Buffer(this.uvs); this.addAttribute('aVertexPosition', this.vertexBuffer) .addAttribute('aTextureCoord', this.uvBuffer) .addIndex([0, 1, 2, 0, 2, 3]); } if ( Geometry ) QuadUv.__proto__ = Geometry; QuadUv.prototype = Object.create( Geometry && Geometry.prototype ); QuadUv.prototype.constructor = QuadUv; /** * Maps two Rectangle to the quad. * * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle * @param {PIXI.Rectangle} destinationFrame - the second rectangle * @return {PIXI.Quad} Returns itself. */ QuadUv.prototype.map = function map (targetTextureFrame, destinationFrame) { var x = 0; // destinationFrame.x / targetTextureFrame.width; var y = 0; // destinationFrame.y / targetTextureFrame.height; this.uvs[0] = x; this.uvs[1] = y; this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width); this.uvs[3] = y; this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width); this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height); this.uvs[6] = x; this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height); x = destinationFrame.x; y = destinationFrame.y; this.vertices[0] = x; this.vertices[1] = y; this.vertices[2] = x + destinationFrame.width; this.vertices[3] = y; this.vertices[4] = x + destinationFrame.width; this.vertices[5] = y + destinationFrame.height; this.vertices[6] = x; this.vertices[7] = y + destinationFrame.height; this.invalidate(); return this; }; /** * legacy upload method, just marks buffers dirty * @returns {PIXI.QuadUv} Returns itself. */ QuadUv.prototype.invalidate = function invalidate () { this.vertexBuffer._updateID++; this.uvBuffer._updateID++; return this; }; return QuadUv; }(Geometry)); var UID$2 = 0; /** * Uniform group holds uniform map and some ID's for work * * @class * @memberof PIXI */ var UniformGroup = function UniformGroup(uniforms, _static) { /** * uniform values * @member {object} * @readonly */ this.uniforms = uniforms; /** * Its a group and not a single uniforms * @member {boolean} * @readonly * @default true */ this.group = true; // lets generate this when the shader ? this.syncUniforms = {}; /** * dirty version * @protected * @member {number} */ this.dirtyId = 0; /** * unique id * @protected * @member {number} */ this.id = UID$2++; /** * Uniforms wont be changed after creation * @member {boolean} */ this.static = !!_static; }; UniformGroup.prototype.update = function update () { this.dirtyId++; }; UniformGroup.prototype.add = function add (name, uniforms, _static) { this.uniforms[name] = new UniformGroup(uniforms, _static); }; UniformGroup.from = function from (uniforms, _static) { return new UniformGroup(uniforms, _static); }; /** * System plugin to the renderer to manage filter states. * * @class * @private */ var FilterState = function FilterState() { this.renderTexture = null; /** * Target of the filters * We store for case when custom filter wants to know the element it was applied on * @member {PIXI.DisplayObject} * @private */ this.target = null; /** * Compatibility with PixiJS v4 filters * @member {boolean} * @default false * @private */ this.legacy = false; /** * Resolution of filters * @member {number} * @default 1 * @private */ this.resolution = 1; // next three fields are created only for root // re-assigned for everything else /** * Source frame * @member {PIXI.Rectangle} * @private */ this.sourceFrame = new math.Rectangle(); /** * Destination frame * @member {PIXI.Rectangle} * @private */ this.destinationFrame = new math.Rectangle(); /** * Collection of filters * @member {PIXI.Filter[]} * @private */ this.filters = []; }; /** * clears the state * @private */ FilterState.prototype.clear = function clear () { this.target = null; this.filters = null; this.renderTexture = null; }; /** * System plugin to the renderer to manage the filters. * * @class * @memberof PIXI.systems * @extends PIXI.System */ var FilterSystem = /*@__PURE__*/(function (System) { function FilterSystem(renderer) { System.call(this, renderer); /** * List of filters for the FilterSystem * @member {Object[]} * @readonly */ this.defaultFilterStack = [{}]; /** * stores a bunch of PO2 textures used for filtering * @member {Object} */ this.texturePool = new RenderTexturePool(); this.texturePool.setScreenSize(renderer.view); /** * a pool for storing filter states, save us creating new ones each tick * @member {Object[]} */ this.statePool = []; /** * A very simple geometry used when drawing a filter effect to the screen * @member {PIXI.Quad} */ this.quad = new Quad(); /** * Quad UVs * @member {PIXI.QuadUv} */ this.quadUv = new QuadUv(); /** * Temporary rect for maths * @type {PIXI.Rectangle} */ this.tempRect = new math.Rectangle(); /** * Active state * @member {object} */ this.activeState = {}; /** * This uniform group is attached to filter uniforms when used * @member {PIXI.UniformGroup} * @property {PIXI.Rectangle} outputFrame * @property {Float32Array} inputSize * @property {Float32Array} inputPixel * @property {Float32Array} inputClamp * @property {Number} resolution * @property {Float32Array} filterArea * @property {Fload32Array} filterClamp */ this.globalUniforms = new UniformGroup({ outputFrame: this.tempRect, inputSize: new Float32Array(4), inputPixel: new Float32Array(4), inputClamp: new Float32Array(4), resolution: 1, // legacy variables filterArea: new Float32Array(4), filterClamp: new Float32Array(4), }, true); this._pixelsWidth = renderer.view.width; this._pixelsHeight = renderer.view.height; } if ( System ) FilterSystem.__proto__ = System; FilterSystem.prototype = Object.create( System && System.prototype ); FilterSystem.prototype.constructor = FilterSystem; /** * Adds a new filter to the System. * * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ FilterSystem.prototype.push = function push (target, filters) { var renderer = this.renderer; var filterStack = this.defaultFilterStack; var state = this.statePool.pop() || new FilterState(); var resolution = filters[0].resolution; var padding = filters[0].padding; var autoFit = filters[0].autoFit; var legacy = filters[0].legacy; for (var i = 1; i < filters.length; i++) { var filter = filters[i]; // lets use the lowest resolution.. resolution = Math.min(resolution, filter.resolution); // and the largest amount of padding! padding = Math.max(padding, filter.padding); // only auto fit if all filters are autofit autoFit = autoFit || filter.autoFit; legacy = legacy || filter.legacy; } if (filterStack.length === 1) { this.defaultFilterStack[0].renderTexture = renderer.renderTexture.current; } filterStack.push(state); state.resolution = resolution; state.legacy = legacy; state.target = target; state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true)); state.sourceFrame.pad(padding); if (autoFit) { state.sourceFrame.fit(this.renderer.renderTexture.sourceFrame); } // round to whole number based on resolution state.sourceFrame.ceil(resolution); state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution); state.filters = filters; state.destinationFrame.width = state.renderTexture.width; state.destinationFrame.height = state.renderTexture.height; state.renderTexture.filterFrame = state.sourceFrame; renderer.renderTexture.bind(state.renderTexture, state.sourceFrame);// /, state.destinationFrame); renderer.renderTexture.clear(); }; /** * Pops off the filter and applies it. * */ FilterSystem.prototype.pop = function pop () { var filterStack = this.defaultFilterStack; var state = filterStack.pop(); var filters = state.filters; this.activeState = state; var globalUniforms = this.globalUniforms.uniforms; globalUniforms.outputFrame = state.sourceFrame; globalUniforms.resolution = state.resolution; var inputSize = globalUniforms.inputSize; var inputPixel = globalUniforms.inputPixel; var inputClamp = globalUniforms.inputClamp; inputSize[0] = state.destinationFrame.width; inputSize[1] = state.destinationFrame.height; inputSize[2] = 1.0 / inputSize[0]; inputSize[3] = 1.0 / inputSize[1]; inputPixel[0] = inputSize[0] * state.resolution; inputPixel[1] = inputSize[1] * state.resolution; inputPixel[2] = 1.0 / inputPixel[0]; inputPixel[3] = 1.0 / inputPixel[1]; inputClamp[0] = 0.5 * inputPixel[2]; inputClamp[1] = 0.5 * inputPixel[3]; inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]); inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]); // only update the rect if its legacy.. if (state.legacy) { var filterArea = globalUniforms.filterArea; filterArea[0] = state.destinationFrame.width; filterArea[1] = state.destinationFrame.height; filterArea[2] = state.sourceFrame.x; filterArea[3] = state.sourceFrame.y; globalUniforms.filterClamp = globalUniforms.inputClamp; } this.globalUniforms.update(); var lastState = filterStack[filterStack.length - 1]; if (filters.length === 1) { filters[0].apply(this, state.renderTexture, lastState.renderTexture, false, state); this.returnFilterTexture(state.renderTexture); } else { var flip = state.renderTexture; var flop = this.getOptimalFilterTexture( flip.width, flip.height, state.resolution ); flop.filterFrame = flip.filterFrame; var i = 0; for (i = 0; i < filters.length - 1; ++i) { filters[i].apply(this, flip, flop, true, state); var t = flip; flip = flop; flop = t; } filters[i].apply(this, flip, lastState.renderTexture, false, state); this.returnFilterTexture(flip); this.returnFilterTexture(flop); } state.clear(); this.statePool.push(state); }; /** * Draws a filter. * * @param {PIXI.Filter} filter - The filter to draw. * @param {PIXI.RenderTexture} input - The input render target. * @param {PIXI.RenderTexture} output - The target to output to. * @param {boolean} clear - Should the output be cleared before rendering to it */ FilterSystem.prototype.applyFilter = function applyFilter (filter, input, output, clear) { var renderer = this.renderer; renderer.renderTexture.bind(output, output ? output.filterFrame : null); if (clear) { // gl.disable(gl.SCISSOR_TEST); renderer.renderTexture.clear(); // gl.enable(gl.SCISSOR_TEST); } // set the uniforms.. filter.uniforms.uSampler = input; filter.uniforms.filterGlobals = this.globalUniforms; // TODO make it so that the order of this does not matter.. // because it does at the moment cos of global uniforms. // they need to get resynced renderer.state.set(filter.state); renderer.shader.bind(filter); if (filter.legacy) { this.quadUv.map(input._frame, input.filterFrame); renderer.geometry.bind(this.quadUv); renderer.geometry.draw(constants.DRAW_MODES.TRIANGLES); } else { renderer.geometry.bind(this.quad); renderer.geometry.draw(constants.DRAW_MODES.TRIANGLE_STRIP); } }; /** * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_. * * Use `outputMatrix * vTextureCoord` in the shader. * * @param {PIXI.Matrix} outputMatrix - The matrix to output to. * @param {PIXI.Sprite} sprite - The sprite to map to. * @return {PIXI.Matrix} The mapped matrix. */ FilterSystem.prototype.calculateSpriteMatrix = function calculateSpriteMatrix (outputMatrix, sprite) { var ref = this.activeState; var sourceFrame = ref.sourceFrame; var destinationFrame = ref.destinationFrame; var ref$1 = sprite._texture; var orig = ref$1.orig; var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, destinationFrame.height, sourceFrame.x, sourceFrame.y); var worldTransform = sprite.worldTransform.copyTo(math.Matrix.TEMP_MATRIX); worldTransform.invert(); mappedMatrix.prepend(worldTransform); mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); return mappedMatrix; }; /** * Destroys this Filter System. */ FilterSystem.prototype.destroy = function destroy () { // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem this.texturePool.clear(false); }; /** * Gets a Power-of-Two render texture or fullScreen texture * * @protected * @param {number} minWidth - The minimum width of the render texture in real pixels. * @param {number} minHeight - The minimum height of the render texture in real pixels. * @param {number} [resolution=1] - The resolution of the render texture. * @return {PIXI.RenderTexture} The new render texture. */ FilterSystem.prototype.getOptimalFilterTexture = function getOptimalFilterTexture (minWidth, minHeight, resolution) { if ( resolution === void 0 ) resolution = 1; return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution); }; /** * Gets extra render texture to use inside current filter * To be compliant with older filters, you can use params in any order * * @param {PIXI.RenderTexture} [input] renderTexture from which size and resolution will be copied * @param {number} [resolution] override resolution of the renderTexture * @returns {PIXI.RenderTexture} */ FilterSystem.prototype.getFilterTexture = function getFilterTexture (input, resolution) { if (typeof input === 'number') { var swap = input; input = resolution; resolution = swap; } input = input || this.activeState.renderTexture; var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution); filterTexture.filterFrame = input.filterFrame; return filterTexture; }; /** * Frees a render texture back into the pool. * * @param {PIXI.RenderTexture} renderTexture - The renderTarget to free */ FilterSystem.prototype.returnFilterTexture = function returnFilterTexture (renderTexture) { this.texturePool.returnTexture(renderTexture); }; /** * Empties the texture pool. */ FilterSystem.prototype.emptyPool = function emptyPool () { this.texturePool.clear(true); }; /** * calls `texturePool.resize()`, affects fullScreen renderTextures */ FilterSystem.prototype.resize = function resize () { this.texturePool.setScreenSize(this.renderer.view); }; return FilterSystem; }(System)); /** * Base for a common object renderer that can be used as a * system renderer plugin. * * @class * @extends PIXI.System * @memberof PIXI */ var ObjectRenderer = function ObjectRenderer(renderer) { /** * The renderer this manager works for. * * @member {PIXI.Renderer} */ this.renderer = renderer; }; /** * Stub method that should be used to empty the current * batch by rendering objects now. */ ObjectRenderer.prototype.flush = function flush () { // flush! }; /** * Generic destruction method that frees all resources. This * should be called by subclasses. */ ObjectRenderer.prototype.destroy = function destroy () { this.renderer = null; }; /** * Stub method that initializes any state required before * rendering starts. It is different from the `prerender` * signal, which occurs every frame, in that it is called * whenever an object requests _this_ renderer specifically. */ ObjectRenderer.prototype.start = function start () { // set the shader.. }; /** * Stops the renderer. It should free up any state and * become dormant. */ ObjectRenderer.prototype.stop = function stop () { this.flush(); }; /** * Keeps the object to render. It doesn't have to be * rendered immediately. * * @param {PIXI.DisplayObject} object - The object to render. */ ObjectRenderer.prototype.render = function render (object) // eslint-disable-line no-unused-vars { // render the object }; /** * System plugin to the renderer to manage batching. * * @class * @extends PIXI.System * @memberof PIXI.systems */ var BatchSystem = /*@__PURE__*/(function (System) { function BatchSystem(renderer) { System.call(this, renderer); /** * An empty renderer. * * @member {PIXI.ObjectRenderer} */ this.emptyRenderer = new ObjectRenderer(renderer); /** * The currently active ObjectRenderer. * * @member {PIXI.ObjectRenderer} */ this.currentRenderer = this.emptyRenderer; } if ( System ) BatchSystem.__proto__ = System; BatchSystem.prototype = Object.create( System && System.prototype ); BatchSystem.prototype.constructor = BatchSystem; /** * Changes the current renderer to the one given in parameter * * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. */ BatchSystem.prototype.setObjectRenderer = function setObjectRenderer (objectRenderer) { if (this.currentRenderer === objectRenderer) { return; } this.currentRenderer.stop(); this.currentRenderer = objectRenderer; this.currentRenderer.start(); }; /** * This should be called if you wish to do some custom rendering * It will basically render anything that may be batched up such as sprites */ BatchSystem.prototype.flush = function flush () { this.setObjectRenderer(this.emptyRenderer); }; /** * Reset the system to an empty renderer */ BatchSystem.prototype.reset = function reset () { this.setObjectRenderer(this.emptyRenderer); }; /** * Handy function for batch renderers: copies bound textures in first maxTextures locations to array * sets actual _batchLocation for them * * @param arr * @param maxTextures */ BatchSystem.prototype.copyBoundTextures = function copyBoundTextures (arr, maxTextures) { var ref = this.renderer.texture; var boundTextures = ref.boundTextures; for (var i = maxTextures - 1; i >= 0; --i) { arr[i] = boundTextures[i] || null; if (arr[i]) { arr[i]._batchLocation = i; } } }; /** * Assigns batch locations to textures in array based on boundTextures state. * All textures in texArray should have `_batchEnabled = _batchId`, * and their count should be less than `maxTextures`. * * @param {PIXI.BatchTextureArray} texArray textures to bound * @param {PIXI.BaseTexture[]} boundTextures current state of bound textures * @param {number} batchId marker for _batchEnabled param of textures in texArray * @param {number} maxTextures number of texture locations to manipulate */ BatchSystem.prototype.boundArray = function boundArray (texArray, boundTextures, batchId, maxTextures) { var elements = texArray.elements; var ids = texArray.ids; var count = texArray.count; var j = 0; for (var i = 0; i < count; i++) { var tex = elements[i]; var loc = tex._batchLocation; if (loc >= 0 && loc < maxTextures && boundTextures[loc] === tex) { ids[i] = loc; continue; } while (j < maxTextures) { var bound = boundTextures[j]; if (bound && bound._batchEnabled === batchId && bound._batchLocation === j) { j++; continue; } ids[i] = j; tex._batchLocation = j; boundTextures[j] = tex; break; } } }; return BatchSystem; }(System)); /** * The maximum support for using WebGL. If a device does not * support WebGL version, for instance WebGL 2, it will still * attempt to fallback support to WebGL 1. If you want to * explicitly remove feature support to target a more stable * baseline, prefer a lower environment. * * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium} * we disable webgl2 by default for all non-apple mobile devices. * * @static * @name PREFER_ENV * @memberof PIXI.settings * @type {number} * @default PIXI.ENV.WEBGL2 */ settings.settings.PREFER_ENV = utils.isMobile.any ? constants.ENV.WEBGL : constants.ENV.WEBGL2; /** * If set to `true`, Textures and BaseTexture objects stored * in the caches ({@link PIXI.utils.TextureCache TextureCache} and * {@link PIXI.utils.BaseTextureCache BaseTextureCache}) can *only* be * used when calling {@link PIXI.Texture.from Texture.from} or * {@link PIXI.BaseTexture.from BaseTexture.from}. * Otherwise, these `from` calls throw an exception. Using this property * can be useful if you want to enforce preloading all assets with * {@link PIXI.Loader Loader}. * * @static * @name STRICT_TEXTURE_CACHE * @memberof PIXI.settings * @type {boolean} * @default false */ settings.settings.STRICT_TEXTURE_CACHE = false; var CONTEXT_UID = 0; /** * System plugin to the renderer to manage the context. * * @class * @extends PIXI.System * @memberof PIXI.systems */ var ContextSystem = /*@__PURE__*/(function (System) { function ContextSystem(renderer) { System.call(this, renderer); /** * Either 1 or 2 to reflect the WebGL version being used * @member {number} * @readonly */ this.webGLVersion = 1; /** * Extensions being used * @member {object} * @readonly * @property {WEBGL_draw_buffers} drawBuffers - WebGL v1 extension * @property {WEBGL_depth_texture} depthTexture - WebGL v1 extension * @property {OES_texture_float} floatTexture - WebGL v1 extension * @property {WEBGL_lose_context} loseContext - WebGL v1 extension * @property {OES_vertex_array_object} vertexArrayObject - WebGL v1 extension * @property {EXT_texture_filter_anisotropic} anisotropicFiltering - WebGL v1 and v2 extension */ this.extensions = {}; // Bind functions this.handleContextLost = this.handleContextLost.bind(this); this.handleContextRestored = this.handleContextRestored.bind(this); renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); } if ( System ) ContextSystem.__proto__ = System; ContextSystem.prototype = Object.create( System && System.prototype ); ContextSystem.prototype.constructor = ContextSystem; var prototypeAccessors = { isLost: { configurable: true } }; /** * `true` if the context is lost * @member {boolean} * @readonly */ prototypeAccessors.isLost.get = function () { return (!this.gl || this.gl.isContextLost()); }; /** * Handle the context change event * @param {WebGLRenderingContext} gl new webgl context */ ContextSystem.prototype.contextChange = function contextChange (gl) { this.gl = gl; this.renderer.gl = gl; this.renderer.CONTEXT_UID = CONTEXT_UID++; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } }; /** * Initialize the context * * @protected * @param {WebGLRenderingContext} gl - WebGL context */ ContextSystem.prototype.initFromContext = function initFromContext (gl) { this.gl = gl; this.validateContext(gl); this.renderer.gl = gl; this.renderer.CONTEXT_UID = CONTEXT_UID++; this.renderer.runners.contextChange.run(gl); }; /** * Initialize from context options * * @protected * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext * @param {object} options - context attributes */ ContextSystem.prototype.initFromOptions = function initFromOptions (options) { var gl = this.createContext(this.renderer.view, options); this.initFromContext(gl); }; /** * Helper class to create a WebGL Context * * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {object} An options object that gets passed in to the canvas element containing the context attributes * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext * @return {WebGLRenderingContext} the WebGL context */ ContextSystem.prototype.createContext = function createContext (canvas, options) { var gl; if (settings.settings.PREFER_ENV >= constants.ENV.WEBGL2) { gl = canvas.getContext('webgl2', options); } if (gl) { this.webGLVersion = 2; } else { this.webGLVersion = 1; gl = canvas.getContext('webgl', options) || canvas.getContext('experimental-webgl', options); if (!gl) { // fail, not able to get a context throw new Error('This browser does not support WebGL. Try using the canvas renderer'); } } this.gl = gl; this.getExtensions(); return gl; }; /** * Auto-populate the extensions * * @protected */ ContextSystem.prototype.getExtensions = function getExtensions () { // time to set up default extensions that Pixi uses. var ref = this; var gl = ref.gl; if (this.webGLVersion === 1) { Object.assign(this.extensions, { drawBuffers: gl.getExtension('WEBGL_draw_buffers'), depthTexture: gl.getExtension('WEBKIT_WEBGL_depth_texture'), loseContext: gl.getExtension('WEBGL_lose_context'), vertexArrayObject: gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'), anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), uint32ElementIndex: gl.getExtension('OES_element_index_uint'), // Floats and half-floats floatTexture: gl.getExtension('OES_texture_float'), floatTextureLinear: gl.getExtension('OES_texture_float_linear'), textureHalfFloat: gl.getExtension('OES_texture_half_float'), textureHalfFloatLinear: gl.getExtension('OES_texture_half_float_linear'), }); } else if (this.webGLVersion === 2) { Object.assign(this.extensions, { anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), // Floats and half-floats colorBufferFloat: gl.getExtension('EXT_color_buffer_float'), floatTextureLinear: gl.getExtension('OES_texture_float_linear'), }); } }; /** * Handles a lost webgl context * * @protected * @param {WebGLContextEvent} event - The context lost event. */ ContextSystem.prototype.handleContextLost = function handleContextLost (event) { event.preventDefault(); }; /** * Handles a restored webgl context * * @protected */ ContextSystem.prototype.handleContextRestored = function handleContextRestored () { this.renderer.runners.contextChange.run(this.gl); }; ContextSystem.prototype.destroy = function destroy () { var view = this.renderer.view; // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); this.gl.useProgram(null); if (this.extensions.loseContext) { this.extensions.loseContext.loseContext(); } }; /** * Handle the post-render runner event * * @protected */ ContextSystem.prototype.postrender = function postrender () { if (this.renderer.renderingToScreen) { this.gl.flush(); } }; /** * Validate context * * @protected * @param {WebGLRenderingContext} gl - Render context */ ContextSystem.prototype.validateContext = function validateContext (gl) { var attributes = gl.getContextAttributes(); // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { /* eslint-disable max-len */ /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ /* eslint-enable max-len */ } }; Object.defineProperties( ContextSystem.prototype, prototypeAccessors ); return ContextSystem; }(System)); /** * System plugin to the renderer to manage framebuffers. * * @class * @extends PIXI.System * @memberof PIXI.systems */ var FramebufferSystem = /*@__PURE__*/(function (System) { function FramebufferSystem(renderer) { System.call(this, renderer); /** * A list of managed framebuffers * @member {PIXI.Framebuffer[]} * @readonly */ this.managedFramebuffers = []; /** * Framebuffer value that shows that we don't know what is bound * @member {Framebuffer} * @readonly */ this.unknownFramebuffer = new Framebuffer(10, 10); } if ( System ) FramebufferSystem.__proto__ = System; FramebufferSystem.prototype = Object.create( System && System.prototype ); FramebufferSystem.prototype.constructor = FramebufferSystem; var prototypeAccessors = { size: { configurable: true } }; /** * Sets up the renderer context and necessary buffers. */ FramebufferSystem.prototype.contextChange = function contextChange () { var gl = this.gl = this.renderer.gl; this.CONTEXT_UID = this.renderer.CONTEXT_UID; this.current = this.unknownFramebuffer; this.viewport = new math.Rectangle(); this.hasMRT = true; this.writeDepthTexture = true; this.disposeAll(true); // webgl2 if (this.renderer.context.webGLVersion === 1) { // webgl 1! var nativeDrawBuffersExtension = this.renderer.context.extensions.drawBuffers; var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture; if (settings.settings.PREFER_ENV === constants.ENV.WEBGL_LEGACY) { nativeDrawBuffersExtension = null; nativeDepthTextureExtension = null; } if (nativeDrawBuffersExtension) { gl.drawBuffers = function (activeTextures) { return nativeDrawBuffersExtension.drawBuffersWEBGL(activeTextures); }; } else { this.hasMRT = false; gl.drawBuffers = function () { // empty }; } if (!nativeDepthTextureExtension) { this.writeDepthTexture = false; } } }; /** * Bind a framebuffer * * @param {PIXI.Framebuffer} framebuffer * @param {PIXI.Rectangle} [frame] frame, default is framebuffer size */ FramebufferSystem.prototype.bind = function bind (framebuffer, frame) { var ref = this; var gl = ref.gl; if (framebuffer) { // TODO caching layer! var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); if (this.current !== framebuffer) { this.current = framebuffer; gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); } // make sure all textures are unbound.. // now check for updates... if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; this.resizeFramebuffer(framebuffer); } } for (var i = 0; i < framebuffer.colorTextures.length; i++) { if (framebuffer.colorTextures[i].texturePart) { this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } if (frame) { this.setViewport(frame.x, frame.y, frame.width, frame.height); } else { this.setViewport(0, 0, framebuffer.width, framebuffer.height); } } else { if (this.current) { this.current = null; gl.bindFramebuffer(gl.FRAMEBUFFER, null); } if (frame) { this.setViewport(frame.x, frame.y, frame.width, frame.height); } else { this.setViewport(0, 0, this.renderer.width, this.renderer.height); } } }; /** * Set the WebGLRenderingContext's viewport. * * @param {Number} x - X position of viewport * @param {Number} y - Y position of viewport * @param {Number} width - Width of viewport * @param {Number} height - Height of viewport */ FramebufferSystem.prototype.setViewport = function setViewport (x, y, width, height) { var v = this.viewport; if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) { v.x = x; v.y = y; v.width = width; v.height = height; this.gl.viewport(x, y, width, height); } }; /** * Get the size of the current width and height. Returns object with `width` and `height` values. * * @member {object} * @readonly */ prototypeAccessors.size.get = function () { if (this.current) { // TODO store temp return { x: 0, y: 0, width: this.current.width, height: this.current.height }; } return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height }; }; /** * Clear the color of the context * * @param {Number} r - Red value from 0 to 1 * @param {Number} g - Green value from 0 to 1 * @param {Number} b - Blue value from 0 to 1 * @param {Number} a - Alpha value from 0 to 1 */ FramebufferSystem.prototype.clear = function clear (r, g, b, a) { var ref = this; var gl = ref.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }; /** * Initialize framebuffer * * @protected * @param {PIXI.Framebuffer} framebuffer */ FramebufferSystem.prototype.initFramebuffer = function initFramebuffer (framebuffer) { var ref = this; var gl = ref.gl; // TODO - make this a class? var fbo = { framebuffer: gl.createFramebuffer(), stencil: null, dirtyId: 0, dirtyFormat: 0, dirtySize: 0, }; framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo; this.managedFramebuffers.push(framebuffer); framebuffer.disposeRunner.add(this); return fbo; }; /** * Resize the framebuffer * * @protected * @param {PIXI.Framebuffer} framebuffer */ FramebufferSystem.prototype.resizeFramebuffer = function resizeFramebuffer (framebuffer) { var ref = this; var gl = ref.gl; var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; if (fbo.stencil) { gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); } var colorTextures = framebuffer.colorTextures; for (var i = 0; i < colorTextures.length; i++) { this.renderer.texture.bind(colorTextures[i], 0); } if (framebuffer.depthTexture) { this.renderer.texture.bind(framebuffer.depthTexture, 0); } }; /** * Update the framebuffer * * @protected * @param {PIXI.Framebuffer} framebuffer */ FramebufferSystem.prototype.updateFramebuffer = function updateFramebuffer (framebuffer) { var ref = this; var gl = ref.gl; var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; // bind the color texture var colorTextures = framebuffer.colorTextures; var count = colorTextures.length; if (!gl.drawBuffers) { count = Math.min(count, 1); } var activeTextures = []; for (var i = 0; i < count; i++) { var texture = framebuffer.colorTextures[i]; if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_CUBE_MAP_NEGATIVE_X + texture.side, texture.texture._glTextures[this.CONTEXT_UID].texture, 0); } else { this.renderer.texture.bind(texture, 0); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, texture._glTextures[this.CONTEXT_UID].texture, 0); } activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } if (activeTextures.length > 1) { gl.drawBuffers(activeTextures); } if (framebuffer.depthTexture) { var writeDepthTexture = this.writeDepthTexture; if (writeDepthTexture) { var depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._glTextures[this.CONTEXT_UID].texture, 0); } } if (!fbo.stencil && (framebuffer.stencil || framebuffer.depth)) { fbo.stencil = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); // TODO.. this is depth AND stencil? if (!framebuffer.depthTexture) { // you can't have both, so one should take priority if enabled gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); } } }; /** * Disposes framebuffer * @param {PIXI.Framebuffer} framebuffer framebuffer that has to be disposed of * @param {boolean} [contextLost=false] If context was lost, we suppress all delete function calls */ FramebufferSystem.prototype.disposeFramebuffer = function disposeFramebuffer (framebuffer, contextLost) { var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; var gl = this.gl; if (!fbo) { return; } delete framebuffer.glFramebuffers[this.CONTEXT_UID]; var index = this.managedFramebuffers.indexOf(framebuffer); if (index >= 0) { this.managedFramebuffers.splice(index, 1); } framebuffer.disposeRunner.remove(this); if (!contextLost) { gl.deleteFramebuffer(fbo.framebuffer); if (fbo.stencil) { gl.deleteRenderbuffer(fbo.stencil); } } }; /** * Disposes all framebuffers, but not textures bound to them * @param {boolean} [contextLost=false] If context was lost, we suppress all delete function calls */ FramebufferSystem.prototype.disposeAll = function disposeAll (contextLost) { var list = this.managedFramebuffers; this.managedFramebuffers = []; for (var i = 0; i < list.length; i++) { this.disposeFramebuffer(list[i], contextLost); } }; /** * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before. * Used by MaskSystem, when its time to use stencil mask for Graphics element. * * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind. * * @private */ FramebufferSystem.prototype.forceStencil = function forceStencil () { var framebuffer = this.current; if (!framebuffer) { return; } var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; if (!fbo || fbo.stencil) { return; } framebuffer.enableStencil(); var w = framebuffer.width; var h = framebuffer.height; var gl = this.gl; var stencil = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h); fbo.stencil = stencil; gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil); }; /** * resets framebuffer stored state, binds screen framebuffer * * should be called before renderTexture reset() */ FramebufferSystem.prototype.reset = function reset () { this.current = this.unknownFramebuffer; this.viewport = new math.Rectangle(); }; Object.defineProperties( FramebufferSystem.prototype, prototypeAccessors ); return FramebufferSystem; }(System)); var GLBuffer = function GLBuffer(buffer) { this.buffer = buffer; this.updateID = -1; this.byteLength = -1; this.refCount = 0; }; var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 }; /** * System plugin to the renderer to manage geometry. * * @class * @extends PIXI.System * @memberof PIXI.systems */ var GeometrySystem = /*@__PURE__*/(function (System) { function GeometrySystem(renderer) { System.call(this, renderer); this._activeGeometry = null; this._activeVao = null; /** * `true` if we has `*_vertex_array_object` extension * @member {boolean} * @readonly */ this.hasVao = true; /** * `true` if has `ANGLE_instanced_arrays` extension * @member {boolean} * @readonly */ this.hasInstance = true; /** * `true` if support `gl.UNSIGNED_INT` in `gl.drawElements` or `gl.drawElementsInstanced` * @member {boolean} * @readonly */ this.canUseUInt32ElementIndex = false; /** * A cache of currently bound buffer, * contains only two members with keys ARRAY_BUFFER and ELEMENT_ARRAY_BUFFER * @member {Object.} * @readonly */ this.boundBuffers = {}; /** * Cache for all geometries by id, used in case renderer gets destroyed or for profiling * @member {object} * @readonly */ this.managedGeometries = {}; /** * Cache for all buffers by id, used in case renderer gets destroyed or for profiling * @member {object} * @readonly */ this.managedBuffers = {}; } if ( System ) GeometrySystem.__proto__ = System; GeometrySystem.prototype = Object.create( System && System.prototype ); GeometrySystem.prototype.constructor = GeometrySystem; /** * Sets up the renderer context and necessary buffers. */ GeometrySystem.prototype.contextChange = function contextChange () { this.disposeAll(true); var gl = this.gl = this.renderer.gl; var context = this.renderer.context; this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 if (!gl.createVertexArray) { // webgl 1! var nativeVaoExtension = this.renderer.context.extensions.vertexArrayObject; if (settings.settings.PREFER_ENV === constants.ENV.WEBGL_LEGACY) { nativeVaoExtension = null; } if (nativeVaoExtension) { gl.createVertexArray = function () { return nativeVaoExtension.createVertexArrayOES(); }; gl.bindVertexArray = function (vao) { return nativeVaoExtension.bindVertexArrayOES(vao); }; gl.deleteVertexArray = function (vao) { return nativeVaoExtension.deleteVertexArrayOES(vao); }; } else { this.hasVao = false; gl.createVertexArray = function () { // empty }; gl.bindVertexArray = function () { // empty }; gl.deleteVertexArray = function () { // empty }; } } if (!gl.vertexAttribDivisor) { var instanceExt = gl.getExtension('ANGLE_instanced_arrays'); if (instanceExt) { gl.vertexAttribDivisor = function (a, b) { return instanceExt.vertexAttribDivisorANGLE(a, b); }; gl.drawElementsInstanced = function (a, b, c, d, e) { return instanceExt.drawElementsInstancedANGLE(a, b, c, d, e); }; gl.drawArraysInstanced = function (a, b, c, d) { return instanceExt.drawArraysInstancedANGLE(a, b, c, d); }; } else { this.hasInstance = false; } } this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex; }; /** * Binds geometry so that is can be drawn. Creating a Vao if required * * @param {PIXI.Geometry} geometry instance of geometry to bind * @param {PIXI.Shader} [shader] instance of shader to use vao for */ GeometrySystem.prototype.bind = function bind (geometry, shader) { shader = shader || this.renderer.shader.shader; var ref = this; var gl = ref.gl; // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; if (!vaos) { this.managedGeometries[geometry.id] = geometry; geometry.disposeRunner.add(this); geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; if (this._activeVao !== vao) { this._activeVao = vao; if (this.hasVao) { gl.bindVertexArray(vao); } else { this.activateVao(geometry, shader.program); } } // TODO - optimise later! // don't need to loop through if nothing changed! // maybe look to add an 'autoupdate' to geometry? this.updateBuffers(); }; /** * Reset and unbind any active VAO and geometry */ GeometrySystem.prototype.reset = function reset () { this.unbind(); }; /** * Update buffers * @protected */ GeometrySystem.prototype.updateBuffers = function updateBuffers () { var geometry = this._activeGeometry; var ref = this; var gl = ref.gl; for (var i = 0; i < geometry.buffers.length; i++) { var buffer = geometry.buffers[i]; var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; if (buffer._updateID !== glBuffer.updateID) { glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? var type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; // TODO this could change if the VAO changes... // need to come up with a better way to cache.. // if (this.boundBuffers[type] !== glBuffer) // { // this.boundBuffers[type] = glBuffer; gl.bindBuffer(type, glBuffer.buffer); // } this._boundBuffer = glBuffer; if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); } else { var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW; glBuffer.byteLength = buffer.data.byteLength; gl.bufferData(type, buffer.data, drawType); } } } }; /** * Check compability between a geometry and a program * @protected * @param {PIXI.Geometry} geometry - Geometry instance * @param {PIXI.Program} program - Program instance */ GeometrySystem.prototype.checkCompatibility = function checkCompatibility (geometry, program) { // geometry must have at least all the attributes that the shader requires. var geometryAttributes = geometry.attributes; var shaderAttributes = program.attributeData; for (var j in shaderAttributes) { if (!geometryAttributes[j]) { throw new Error(("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute")); } } }; /** * Takes a geometry and program and generates a unique signature for them. * * @param {PIXI.Geometry} geometry to get signature from * @param {PIXI.Program} program to test geometry against * @returns {String} Unique signature of the geometry and program * @protected */ GeometrySystem.prototype.getSignature = function getSignature (geometry, program) { var attribs = geometry.attributes; var shaderAttributes = program.attributeData; var strings = ['g', geometry.id]; for (var i in attribs) { if (shaderAttributes[i]) { strings.push(i); } } return strings.join('-'); }; /** * Creates or gets Vao with the same structure as the geometry and stores it on the geometry. * If vao is created, it is bound automatically. * * @protected * @param {PIXI.Geometry} geometry - Instance of geometry to to generate Vao for * @param {PIXI.Program} program - Instance of program */ GeometrySystem.prototype.initGeometryVao = function initGeometryVao (geometry, program) { this.checkCompatibility(geometry, program); var gl = this.gl; var CONTEXT_UID = this.CONTEXT_UID; var signature = this.getSignature(geometry, program); var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID]; var vao = vaoObjectHash[signature]; if (vao) { // this will give us easy access to the vao vaoObjectHash[program.id] = vao; return vao; } var buffers = geometry.buffers; var attributes = geometry.attributes; var tempStride = {}; var tempStart = {}; for (var j in buffers) { tempStride[j] = 0; tempStart[j] = 0; } for (var j$1 in attributes) { if (!attributes[j$1].size && program.attributeData[j$1]) { attributes[j$1].size = program.attributeData[j$1].size; } else if (!attributes[j$1].size) { console.warn(("PIXI Geometry attribute '" + j$1 + "' size cannot be determined (likely the bound shader does not have the attribute)")); // eslint-disable-line } tempStride[attributes[j$1].buffer] += attributes[j$1].size * byteSizeMap$1[attributes[j$1].type]; } for (var j$2 in attributes) { var attribute = attributes[j$2]; var attribSize = attribute.size; if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap$1[attribute.type]) { attribute.stride = 0; } else { attribute.stride = tempStride[attribute.buffer]; } } if (attribute.start === undefined) { attribute.start = tempStart[attribute.buffer]; tempStart[attribute.buffer] += attribSize * byteSizeMap$1[attribute.type]; } } vao = gl.createVertexArray(); gl.bindVertexArray(vao); // first update - and create the buffers! // only create a gl buffer if it actually gets for (var i = 0; i < buffers.length; i++) { var buffer = buffers[i]; if (!buffer._glBuffers[CONTEXT_UID]) { buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer()); this.managedBuffers[buffer.id] = buffer; buffer.disposeRunner.add(this); } buffer._glBuffers[CONTEXT_UID].refCount++; } // TODO - maybe make this a data object? // lets wait to see if we need to first! this.activateVao(geometry, program); this._activeVao = vao; // add it to the cache! vaoObjectHash[program.id] = vao; vaoObjectHash[signature] = vao; return vao; }; /** * Disposes buffer * @param {PIXI.Buffer} buffer buffer with data * @param {boolean} [contextLost=false] If context was lost, we suppress deleteVertexArray */ GeometrySystem.prototype.disposeBuffer = function disposeBuffer (buffer, contextLost) { if (!this.managedBuffers[buffer.id]) { return; } delete this.managedBuffers[buffer.id]; var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; var gl = this.gl; buffer.disposeRunner.remove(this); if (!glBuffer) { return; } if (!contextLost) { gl.deleteBuffer(glBuffer.buffer); } delete buffer._glBuffers[this.CONTEXT_UID]; }; /** * Disposes geometry * @param {PIXI.Geometry} geometry Geometry with buffers. Only VAO will be disposed * @param {boolean} [contextLost=false] If context was lost, we suppress deleteVertexArray */ GeometrySystem.prototype.disposeGeometry = function disposeGeometry (geometry, contextLost) { if (!this.managedGeometries[geometry.id]) { return; } delete this.managedGeometries[geometry.id]; var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; var gl = this.gl; var buffers = geometry.buffers; geometry.disposeRunner.remove(this); if (!vaos) { return; } for (var i = 0; i < buffers.length; i++) { var buf = buffers[i]._glBuffers[this.CONTEXT_UID]; buf.refCount--; if (buf.refCount === 0 && !contextLost) { this.disposeBuffer(buffers[i], contextLost); } } if (!contextLost) { for (var vaoId in vaos) { // delete only signatures, everything else are copies if (vaoId[0] === 'g') { var vao = vaos[vaoId]; if (this._activeVao === vao) { this.unbind(); } gl.deleteVertexArray(vao); } } } delete geometry.glVertexArrayObjects[this.CONTEXT_UID]; }; /** * dispose all WebGL resources of all managed geometries and buffers * @param {boolean} [contextLost=false] If context was lost, we suppress `gl.delete` calls */ GeometrySystem.prototype.disposeAll = function disposeAll (contextLost) { var all = Object.keys(this.managedGeometries); for (var i = 0; i < all.length; i++) { this.disposeGeometry(this.managedGeometries[all[i]], contextLost); } all = Object.keys(this.managedBuffers); for (var i$1 = 0; i$1 < all.length; i$1++) { this.disposeBuffer(this.managedBuffers[all[i$1]], contextLost); } }; /** * Activate vertex array object * * @protected * @param {PIXI.Geometry} geometry - Geometry instance * @param {PIXI.Program} program - Shader program instance */ GeometrySystem.prototype.activateVao = function activateVao (geometry, program) { var gl = this.gl; var CONTEXT_UID = this.CONTEXT_UID; var buffers = geometry.buffers; var attributes = geometry.attributes; if (geometry.indexBuffer) { // first update the index buffer if we have one.. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, geometry.indexBuffer._glBuffers[CONTEXT_UID].buffer); } var lastBuffer = null; // add a new one! for (var j in attributes) { var attribute = attributes[j]; var buffer = buffers[attribute.buffer]; var glBuffer = buffer._glBuffers[CONTEXT_UID]; if (program.attributeData[j]) { if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); lastBuffer = glBuffer; } var location = program.attributeData[j].location; // TODO introduce state again // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, attribute.size, attribute.type || gl.FLOAT, attribute.normalized, attribute.stride, attribute.start); if (attribute.instance) { // TODO calculate instance count based of this... if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } else { throw new Error('geometry error, GPU Instancing is not supported on this device'); } } } } }; /** * Draw the geometry * * @param {Number} type - the type primitive to render * @param {Number} [size] - the number of elements to be rendered * @param {Number} [start] - Starting index * @param {Number} [instanceCount] - the number of instances of the set of elements to execute */ GeometrySystem.prototype.draw = function draw (type, size, start, instanceCount) { var ref = this; var gl = ref.gl; var geometry = this._activeGeometry; // TODO.. this should not change so maybe cache the function? if (geometry.indexBuffer) { var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT; var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT; if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex)) { if (geometry.instanced) { /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1); /* eslint-enable max-len */ } else { /* eslint-disable max-len */ gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize); /* eslint-enable max-len */ } } else { console.warn('unsupported index buffer type: uint32'); } } else if (geometry.instanced) { // TODO need a better way to calculate size.. gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); } else { gl.drawArrays(type, start, size || geometry.getSize()); } return this; }; /** * Unbind/reset everything * @protected */ GeometrySystem.prototype.unbind = function unbind () { this.gl.bindVertexArray(null); this._activeVao = null; this._activeGeometry = null; }; return GeometrySystem; }(System)); /** * Component for masked elements * * Holds mask mode and temporary data about current mask * * @class * @memberof PIXI */ var MaskData = function MaskData(maskObject) { /** * Mask type * @member {PIXI.MASK_TYPES} */ this.type = constants.MASK_TYPES.NONE; /** * Whether we know the mask type beforehand * @member {boolean} * @default true */ this.autoDetect = true; /** * Which element we use to mask * @member {PIXI.DisplayObject} */ this.maskObject = maskObject || null; /** * Whether it belongs to MaskSystem pool * @member {boolean} */ this.pooled = false; /** * Indicator of the type * @member {boolean} */ this.isMaskData = true; /** * Stencil counter above the mask in stack * @member {number} * @private */ this._stencilCounter = 0; /** * Scissor counter above the mask in stack * @member {number} * @private */ this._scissorCounter = 0; /** * Scissor operation above the mask in stack. * Null if _scissorCounter is zero, rectangle instance if positive. * @member {PIXI.Rectangle} */ this._scissorRect = null; /** * Targeted element. Temporary variable set by MaskSystem * @member {PIXI.DisplayObject} * @private */ this._target = null; }; /** * resets the mask data after popMask() */ MaskData.prototype.reset = function reset () { if (this.pooled) { this.maskObject = null; this.type = constants.MASK_TYPES.NONE; this.autoDetect = true; } this._target = null; }; /** * copies counters from maskData above, called from pushMask() * @param {PIXI.MaskData|null} maskAbove */ MaskData.prototype.copyCountersOrReset = function copyCountersOrReset (maskAbove) { if (maskAbove) { this._stencilCounter = maskAbove._stencilCounter; this._scissorCounter = maskAbove._scissorCounter; this._scissorRect = maskAbove._scissorRect; } else { this._stencilCounter = 0; this._scissorCounter = 0; this._scissorRect = null; } }; /** * @method compileProgram * @private * @memberof PIXI.glCore.shader * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); var program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. if (attributeLocations) { for (var i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } gl.linkProgram(program); // if linking fails, then log and cleanup if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { if (!gl.getShaderParameter(glVertShader, gl.COMPILE_STATUS)) { console.warn(vertexSrc); console.error(gl.getShaderInfoLog(glVertShader)); } if (!gl.getShaderParameter(glFragShader, gl.COMPILE_STATUS)) { console.warn(fragmentSrc); console.error(gl.getShaderInfoLog(glFragShader)); } console.error('Pixi.js Error: Could not initialize shader.'); console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); console.error('gl.getError()', gl.getError()); // if there is a program info log, log it if (gl.getProgramInfoLog(program) !== '') { console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } gl.deleteProgram(program); program = null; } // clean up some shaders gl.deleteShader(glVertShader); gl.deleteShader(glFragShader); return program; } /** * @private * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ function compileShader(gl, type, src) { var shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); return shader; } /** * @method defaultValue * @memberof PIXI.glCore.shader * @param type {String} Type of value * @param size {Number} * @private */ function defaultValue(type, size) { switch (type) { case 'float': return 0; case 'vec2': return new Float32Array(2 * size); case 'vec3': return new Float32Array(3 * size); case 'vec4': return new Float32Array(4 * size); case 'int': case 'sampler2D': case 'sampler2DArray': return 0; case 'ivec2': return new Int32Array(2 * size); case 'ivec3': return new Int32Array(3 * size); case 'ivec4': return new Int32Array(4 * size); case 'bool': return false; case 'bvec2': return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); case 'bvec4': return booleanArray(4 * size); case 'mat2': return new Float32Array([1, 0, 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); } return null; } function booleanArray(size) { var array = new Array(size); for (var i = 0; i < array.length; i++) { array[i] = false; } return array; } var unknownContext = {}; var context = unknownContext; /** * returns a little WebGL context to use for program inspection. * * @static * @private * @returns {WebGLRenderingContext} a gl context to test with */ function getTestContext() { if (context === unknownContext || (context && context.isContextLost())) { var canvas = document.createElement('canvas'); var gl; if (settings.settings.PREFER_ENV >= constants.ENV.WEBGL2) { gl = canvas.getContext('webgl2', {}); } if (!gl) { gl = canvas.getContext('webgl', {}) || canvas.getContext('experimental-webgl', {}); if (!gl) { // fail, not able to get a context gl = null; } else { // for shader testing.. gl.getExtension('WEBGL_draw_buffers'); } } context = gl; } return context; } var maxFragmentPrecision; function getMaxFragmentPrecision() { if (!maxFragmentPrecision) { maxFragmentPrecision = constants.PRECISION.MEDIUM; var gl = getTestContext(); if (gl) { if (gl.getShaderPrecisionFormat) { var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); maxFragmentPrecision = shaderFragment.precision ? constants.PRECISION.HIGH : constants.PRECISION.MEDIUM; } } } return maxFragmentPrecision; } /** * Sets the float precision on the shader, ensuring the device supports the request precision. * If the precision is already present, it just ensures that the device is able to handle it. * * @private * @param {string} src - The shader source * @param {string} requestedPrecision - The request float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. * @param {string} maxSupportedPrecision - The maximum precision the shader supports. * * @return {string} modified shader source */ function setPrecision(src, requestedPrecision, maxSupportedPrecision) { if (src.substring(0, 9) !== 'precision') { // no precision supplied, so PixiJS will add the requested level. var precision = requestedPrecision; // If highp is requested but not supported, downgrade precision to a level all devices support. if (requestedPrecision === constants.PRECISION.HIGH && maxSupportedPrecision !== constants.PRECISION.HIGH) { precision = constants.PRECISION.MEDIUM; } return ("precision " + precision + " float;\n" + src); } else if (maxSupportedPrecision !== constants.PRECISION.HIGH && src.substring(0, 15) === 'precision highp') { // precision was supplied, but at a level this device does not support, so downgrading to mediump. return src.replace('precision highp', 'precision mediump'); } return src; } var GLSL_TO_SIZE = { float: 1, vec2: 2, vec3: 3, vec4: 4, int: 1, ivec2: 2, ivec3: 3, ivec4: 4, bool: 1, bvec2: 2, bvec3: 3, bvec4: 4, mat2: 4, mat3: 9, mat4: 16, sampler2D: 1, }; /** * @private * @method mapSize * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ function mapSize(type) { return GLSL_TO_SIZE[type]; } var GL_TABLE = null; var GL_TO_GLSL_TYPES = { FLOAT: 'float', FLOAT_VEC2: 'vec2', FLOAT_VEC3: 'vec3', FLOAT_VEC4: 'vec4', INT: 'int', INT_VEC2: 'ivec2', INT_VEC3: 'ivec3', INT_VEC4: 'ivec4', BOOL: 'bool', BOOL_VEC2: 'bvec2', BOOL_VEC3: 'bvec3', BOOL_VEC4: 'bvec4', FLOAT_MAT2: 'mat2', FLOAT_MAT3: 'mat3', FLOAT_MAT4: 'mat4', SAMPLER_2D: 'sampler2D', SAMPLER_CUBE: 'samplerCube', SAMPLER_2D_ARRAY: 'sampler2DArray', }; function mapType(gl, type) { if (!GL_TABLE) { var typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; for (var i = 0; i < typeNames.length; ++i) { var tn = typeNames[i]; GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } return GL_TABLE[type]; } // cv = CachedValue // v = value // ud = uniformData // uv = uniformValue // l = location var GLSL_TO_SINGLE_SETTERS_CACHED = { float: "\n if(cv !== v)\n {\n cv.v = v;\n gl.uniform1f(location, v)\n }", vec2: "\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(location, v[0], v[1])\n }", vec3: "\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }", vec4: 'gl.uniform4f(location, v[0], v[1], v[2], v[3])', int: 'gl.uniform1i(location, v)', ivec2: 'gl.uniform2i(location, v[0], v[1])', ivec3: 'gl.uniform3i(location, v[0], v[1], v[2])', ivec4: 'gl.uniform4i(location, v[0], v[1], v[2], v[3])', bool: 'gl.uniform1i(location, v)', bvec2: 'gl.uniform2i(location, v[0], v[1])', bvec3: 'gl.uniform3i(location, v[0], v[1], v[2])', bvec4: 'gl.uniform4i(location, v[0], v[1], v[2], v[3])', mat2: 'gl.uniformMatrix2fv(location, false, v)', mat3: 'gl.uniformMatrix3fv(location, false, v)', mat4: 'gl.uniformMatrix4fv(location, false, v)', sampler2D: 'gl.uniform1i(location, v)', samplerCube: 'gl.uniform1i(location, v)', sampler2DArray: 'gl.uniform1i(location, v)', }; var GLSL_TO_ARRAY_SETTERS = { float: "gl.uniform1fv(location, v)", vec2: "gl.uniform2fv(location, v)", vec3: "gl.uniform3fv(location, v)", vec4: 'gl.uniform4fv(location, v)', mat4: 'gl.uniformMatrix4fv(location, false, v)', mat3: 'gl.uniformMatrix3fv(location, false, v)', mat2: 'gl.uniformMatrix2fv(location, false, v)', int: 'gl.uniform1iv(location, v)', ivec2: 'gl.uniform2iv(location, v)', ivec3: 'gl.uniform3iv(location, v)', ivec4: 'gl.uniform4iv(location, v)', bool: 'gl.uniform1iv(location, v)', bvec2: 'gl.uniform2iv(location, v)', bvec3: 'gl.uniform3iv(location, v)', bvec4: 'gl.uniform4iv(location, v)', sampler2D: 'gl.uniform1iv(location, v)', samplerCube: 'gl.uniform1iv(location, v)', sampler2DArray: 'gl.uniform1iv(location, v)', }; function generateUniformsSync(group, uniformData) { var func = "var v = null;\n var cv = null\n var t = 0;\n var gl = renderer.gl\n "; for (var i in group.uniforms) { var data = uniformData[i]; if (!data) { if (group.uniforms[i].group) { func += "\n renderer.shader.syncUniformGroup(uv." + i + ", syncData);\n "; } continue; } // TODO && uniformData[i].value !== 0 <-- do we still need this? if (data.type === 'float' && data.size === 1) { func += "\n if(uv." + i + " !== ud." + i + ".value)\n {\n ud." + i + ".value = uv." + i + "\n gl.uniform1f(ud." + i + ".location, uv." + i + ")\n }\n"; } /* eslint-disable max-len */ else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) /* eslint-disable max-len */ { func += "\n\n t = syncData.textureCount++;\n\n renderer.texture.bind(uv." + i + ", t);\n \n if(ud." + i + ".value !== t)\n {\n ud." + i + ".value = t;\n gl.uniform1i(ud." + i + ".location, t);\n; // eslint-disable-line max-len\n }\n"; } else if (data.type === 'mat3' && data.size === 1) { if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += "\n gl.uniformMatrix3fv(ud." + i + ".location, false, uv." + i + ".toArray(true));\n \n"; } else { func += "\n gl.uniformMatrix3fv(ud." + i + ".location, false, uv." + i + ");\n \n"; } } else if (data.type === 'vec2' && data.size === 1) { // TODO - do we need both here? // maybe we can get away with only using points? if (group.uniforms[i].x !== undefined) { func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud." + i + ".location, v.x, v.y);\n }\n"; } else { func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud." + i + ".location, v[0], v[1]);\n }\n \n"; } } else if (data.type === 'vec4' && data.size === 1) { // TODO - do we need both here? // maybe we can get away with only using points? if (group.uniforms[i].width !== undefined) { func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud." + i + ".location, v.x, v.y, v.width, v.height)\n }\n"; } else { func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud." + i + ".location, v[0], v[1], v[2], v[3])\n }\n \n"; } } else { var templateType = (data.size === 1) ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS; var template = templateType[data.type].replace('location', ("ud." + i + ".location")); func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n " + template + ";\n"; } } /** * the introduction of syncData is to solve an issue where textures in uniform groups are not set correctly * the texture count was always starting from 0 in each group. This needs to increment each time a texture is used * no matter which group is being used * */ return new Function('ud', 'uv', 'renderer', 'syncData', func); // eslint-disable-line no-new-func } var fragTemplate = [ 'precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}' ].join('\n'); function checkMaxIfStatementsInShader(maxIfs, gl) { if (maxIfs === 0) { throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); } var shader = gl.createShader(gl.FRAGMENT_SHADER); while (true) // eslint-disable-line no-constant-condition { var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); gl.shaderSource(shader, fragmentSrc); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { maxIfs = (maxIfs / 2) | 0; } else { // valid! break; } } return maxIfs; } function generateIfTestSrc(maxIfs) { var src = ''; for (var i = 0; i < maxIfs; ++i) { if (i > 0) { src += '\nelse '; } if (i < maxIfs - 1) { src += "if(test == " + i + ".0){}"; } } return src; } // Cache the result to prevent running this over and over var unsafeEval; /** * Not all platforms allow to generate function code (e.g., `new Function`). * this provides the platform-level detection. * * @private * @returns {boolean} */ function unsafeEvalSupported() { if (typeof unsafeEval === 'boolean') { return unsafeEval; } try { /* eslint-disable no-new-func */ var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;'); /* eslint-enable no-new-func */ unsafeEval = func({ a: 'b' }, 'a', 'b') === true; } catch (e) { unsafeEval = false; } return unsafeEval; } var defaultFragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"; var defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"; // import * as from '../systems/shader/shader'; var UID$3 = 0; var nameCache = {}; /** * Helper class to create a shader program. * * @class * @memberof PIXI */ var Program = function Program(vertexSrc, fragmentSrc, name) { if ( name === void 0 ) name = 'pixi-shader'; this.id = UID$3++; /** * The vertex shader. * * @member {string} */ this.vertexSrc = vertexSrc || Program.defaultVertexSrc; /** * The fragment shader. * * @member {string} */ this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc; this.vertexSrc = this.vertexSrc.trim(); this.fragmentSrc = this.fragmentSrc.trim(); if (this.vertexSrc.substring(0, 8) !== '#version') { name = name.replace(/\s+/g, '-'); if (nameCache[name]) { nameCache[name]++; name += "-" + (nameCache[name]); } else { nameCache[name] = 1; } this.vertexSrc = "#define SHADER_NAME " + name + "\n" + (this.vertexSrc); this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + (this.fragmentSrc); this.vertexSrc = setPrecision(this.vertexSrc, settings.settings.PRECISION_VERTEX, constants.PRECISION.HIGH); this.fragmentSrc = setPrecision(this.fragmentSrc, settings.settings.PRECISION_FRAGMENT, getMaxFragmentPrecision()); } // currently this does not extract structs only default types this.extractData(this.vertexSrc, this.fragmentSrc); // this is where we store shader references.. this.glPrograms = {}; this.syncUniforms = null; }; var staticAccessors = { defaultVertexSrc: { configurable: true },defaultFragmentSrc: { configurable: true } }; /** * Extracts the data for a buy creating a small test program * or reading the src directly. * @protected * * @param {string} [vertexSrc] - The source of the vertex shader. * @param {string} [fragmentSrc] - The source of the fragment shader. */ Program.prototype.extractData = function extractData (vertexSrc, fragmentSrc) { var gl = getTestContext(); if (gl) { var program = compileProgram(gl, vertexSrc, fragmentSrc); this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); gl.deleteProgram(program); } else { this.uniformData = {}; this.attributeData = {}; } }; /** * returns the attribute data from the program * @private * * @param {WebGLProgram} [program] - the WebGL program * @param {WebGLRenderingContext} [gl] - the WebGL context * * @returns {object} the attribute data for this program */ Program.prototype.getAttributeData = function getAttributeData (program, gl) { var attributes = {}; var attributesArray = []; var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); for (var i = 0; i < totalAttributes; i++) { var attribData = gl.getActiveAttrib(program, i); var type = mapType(gl, attribData.type); /*eslint-disable */ var data = { type: type, name: attribData.name, size: mapSize(type), location: 0, }; /* eslint-enable */ attributes[attribData.name] = data; attributesArray.push(data); } attributesArray.sort(function (a, b) { return (a.name > b.name) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow for (var i$1 = 0; i$1 < attributesArray.length; i$1++) { attributesArray[i$1].location = i$1; } return attributes; }; /** * returns the uniform data from the program * @private * * @param {webGL-program} [program] - the webgl program * @param {context} [gl] - the WebGL context * * @returns {object} the uniform data for this program */ Program.prototype.getUniformData = function getUniformData (program, gl) { var uniforms = {}; var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (var i = 0; i < totalUniforms; i++) { var uniformData = gl.getActiveUniform(program, i); var name = uniformData.name.replace(/\[.*?\]/, ''); var isArray = uniformData.name.match(/\[.*?\]/, ''); var type = mapType(gl, uniformData.type); /*eslint-disable */ uniforms[name] = { type: type, size: uniformData.size, isArray:isArray, value: defaultValue(type, uniformData.size), }; /* eslint-enable */ } return uniforms; }; /** * The default vertex shader source * * @static * @constant * @member {string} */ staticAccessors.defaultVertexSrc.get = function () { return defaultVertex; }; /** * The default fragment shader source * * @static * @constant * @member {string} */ staticAccessors.defaultFragmentSrc.get = function () { return defaultFragment; }; /** * A short hand function to create a program based of a vertex and fragment shader * this method will also check to see if there is a cached program. * * @param {string} [vertexSrc] - The source of the vertex shader. * @param {string} [fragmentSrc] - The source of the fragment shader. * @param {string} [name=pixi-shader] - Name for shader * * @returns {PIXI.Program} an shiny new Pixi shader! */ Program.from = function from (vertexSrc, fragmentSrc, name) { var key = vertexSrc + fragmentSrc; var program = utils.ProgramCache[key]; if (!program) { utils.ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name); } return program; }; Object.defineProperties( Program, staticAccessors ); /** * A helper class for shaders * * @class * @memberof PIXI */ var Shader = function Shader(program, uniforms) { /** * Program that the shader uses * * @member {PIXI.Program} */ this.program = program; // lets see whats been passed in // uniforms should be converted to a uniform group if (uniforms) { if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { this.uniformGroup = new UniformGroup(uniforms); } } else { this.uniformGroup = new UniformGroup({}); } // time to build some getters and setters! // I guess down the line this could sort of generate an instruction list rather than use dirty ids? // does the trick for now though! for (var i in program.uniformData) { if (this.uniformGroup.uniforms[i] instanceof Array) { this.uniformGroup.uniforms[i] = new Float32Array(this.uniformGroup.uniforms[i]); } } }; var prototypeAccessors$2 = { uniforms: { configurable: true } }; // TODO move to shader system.. Shader.prototype.checkUniformExists = function checkUniformExists (name, group) { if (group.uniforms[name]) { return true; } for (var i in group.uniforms) { var uniform = group.uniforms[i]; if (uniform.group) { if (this.checkUniformExists(name, uniform)) { return true; } } } return false; }; Shader.prototype.destroy = function destroy () { // usage count on programs? // remove if not used! this.uniformGroup = null; }; /** * Shader uniform values, shortcut for `uniformGroup.uniforms` * @readonly * @member {object} */ prototypeAccessors$2.uniforms.get = function () { return this.uniformGroup.uniforms; }; /** * A short hand function to create a shader based of a vertex and fragment shader * * @param {string} [vertexSrc] - The source of the vertex shader. * @param {string} [fragmentSrc] - The source of the fragment shader. * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. * * @returns {PIXI.Shader} an shiny new Pixi shader! */ Shader.from = function from (vertexSrc, fragmentSrc, uniforms) { var program = Program.from(vertexSrc, fragmentSrc); return new Shader(program, uniforms); }; Object.defineProperties( Shader.prototype, prototypeAccessors$2 ); /* eslint-disable max-len */ var BLEND = 0; var OFFSET = 1; var CULLING = 2; var DEPTH_TEST = 3; var WINDING = 4; /** * This is a WebGL state, and is is passed The WebGL StateManager. * * Each mesh rendered may require WebGL to be in a different state. * For example you may want different blend mode or to enable polygon offsets * * @class * @memberof PIXI */ var State = function State() { this.data = 0; this.blendMode = constants.BLEND_MODES.NORMAL; this.polygonOffset = 0; this.blend = true; // this.depthTest = true; }; var prototypeAccessors$3 = { blend: { configurable: true },offsets: { configurable: true },culling: { configurable: true },depthTest: { configurable: true },clockwiseFrontFace: { configurable: true },blendMode: { configurable: true },polygonOffset: { configurable: true } }; /** * Activates blending of the computed fragment color values * * @member {boolean} */ prototypeAccessors$3.blend.get = function () { return !!(this.data & (1 << BLEND)); }; prototypeAccessors$3.blend.set = function (value) // eslint-disable-line require-jsdoc { if (!!(this.data & (1 << BLEND)) !== value) { this.data ^= (1 << BLEND); } }; /** * Activates adding an offset to depth values of polygon's fragments * * @member {boolean} * @default false */ prototypeAccessors$3.offsets.get = function () { return !!(this.data & (1 << OFFSET)); }; prototypeAccessors$3.offsets.set = function (value) // eslint-disable-line require-jsdoc { if (!!(this.data & (1 << OFFSET)) !== value) { this.data ^= (1 << OFFSET); } }; /** * Activates culling of polygons. * * @member {boolean} * @default false */ prototypeAccessors$3.culling.get = function () { return !!(this.data & (1 << CULLING)); }; prototypeAccessors$3.culling.set = function (value) // eslint-disable-line require-jsdoc { if (!!(this.data & (1 << CULLING)) !== value) { this.data ^= (1 << CULLING); } }; /** * Activates depth comparisons and updates to the depth buffer. * * @member {boolean} * @default false */ prototypeAccessors$3.depthTest.get = function () { return !!(this.data & (1 << DEPTH_TEST)); }; prototypeAccessors$3.depthTest.set = function (value) // eslint-disable-line require-jsdoc { if (!!(this.data & (1 << DEPTH_TEST)) !== value) { this.data ^= (1 << DEPTH_TEST); } }; /** * Specifies whether or not front or back-facing polygons can be culled. * @member {boolean} * @default false */ prototypeAccessors$3.clockwiseFrontFace.get = function () { return !!(this.data & (1 << WINDING)); }; prototypeAccessors$3.clockwiseFrontFace.set = function (value) // eslint-disable-line require-jsdoc { if (!!(this.data & (1 << WINDING)) !== value) { this.data ^= (1 << WINDING); } }; /** * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. * Setting this mode to anything other than NO_BLEND will automatically switch blending on. * * @member {number} * @default PIXI.BLEND_MODES.NORMAL * @see PIXI.BLEND_MODES */ prototypeAccessors$3.blendMode.get = function () { return this._blendMode; }; prototypeAccessors$3.blendMode.set = function (value) // eslint-disable-line require-jsdoc { this.blend = (value !== constants.BLEND_MODES.NONE); this._blendMode = value; }; /** * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill. * * @member {number} * @default 0 */ prototypeAccessors$3.polygonOffset.get = function () { return this._polygonOffset; }; prototypeAccessors$3.polygonOffset.set = function (value) // eslint-disable-line require-jsdoc { this.offsets = !!value; this._polygonOffset = value; }; State.for2d = function for2d () { var state = new State(); state.depthTest = false; state.blend = true; return state; }; Object.defineProperties( State.prototype, prototypeAccessors$3 ); var defaultVertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"; /** * Filter is a special type of WebGL shader that is applied to the screen. * * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the * {@link PIXI.filters.BlurFilter BlurFilter}. * * ### Usage * Filters can be applied to any DisplayObject or Container. * PixiJS' `FilterSystem` renders the container into temporary Framebuffer, * then filter renders it to the screen. * Multiple filters can be added to the `filters` array property and stacked on each other. * * ``` * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 }); * const container = new PIXI.Container(); * container.filters = [filter]; * ``` * * ### Previous Version Differences * * In PixiJS **v3**, a filter was always applied to _whole screen_. * * In PixiJS **v4**, a filter can be applied _only part of the screen_. * Developers had to create a set of uniforms to deal with coordinates. * * In PixiJS **v5** combines _both approaches_. * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers, * bringing those extra uniforms into account. * * Also be aware that we have changed default vertex shader, please consult * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. * * ### Built-in Uniforms * * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`, * and `projectionMatrix` uniform maps it to the gl viewport. * * **uSampler** * * The most important uniform is the input texture that container was rendered into. * _Important note: as with all Framebuffers in PixiJS, both input and output are * premultiplied by alpha._ * * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`. * Use it to sample the input. * * ``` * const fragment = ` * varying vec2 vTextureCoord; * uniform sampler2D uSampler; * void main(void) * { * gl_FragColor = texture2D(uSampler, vTextureCoord); * } * `; * * const myFilter = new PIXI.Filter(null, fragment); * ``` * * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}. * * **outputFrame** * * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates. * It's the same as `renderer.screen` for a fullscreen filter. * Only a part of `outputFrame.zw` size of temporary Framebuffer is used, * `(0, 0, outputFrame.width, outputFrame.height)`, * * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute. * To calculate vertex position in screen space using normalized (0-1) space: * * ``` * vec4 filterVertexPosition( void ) * { * vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy; * return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); * } * ``` * * **inputSize** * * Temporary framebuffer is different, it can be either the size of screen, either power-of-two. * The `inputSize.xy` are size of temporary framebuffer that holds input. * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader. * * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter. * * To calculate input normalized coordinate, you have to map it to filter normalized space. * Multiply by `outputFrame.zw` to get input coordinate. * Divide by `inputSize.xy` to get input normalized coordinate. * * ``` * vec2 filterTextureCoord( void ) * { * return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy * } * ``` * **resolution** * * The `resolution` is the ratio of screen (CSS) pixels to real pixels. * * **inputPixel** * * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution` * `inputPixel.zw` is inverted `inputPixel.xy`. * * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}. * * **inputClamp** * * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour. * For displacements, coordinates has to be clamped. * * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer * `inputClamp.zw` is bottom-right pixel center. * * ``` * vec4 color = texture2D(uSampler, clamp(modifigedTextureCoord, inputClamp.xy, inputClamp.zw)) * ``` * OR * ``` * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw)) * ``` * * ### Additional Information * * Complete documentation on Filter usage is located in the * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. * * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository. * * @class * @memberof PIXI * @extends PIXI.Shader */ var Filter = /*@__PURE__*/(function (Shader) { function Filter(vertexSrc, fragmentSrc, uniforms) { var program = Program.from(vertexSrc || Filter.defaultVertexSrc, fragmentSrc || Filter.defaultFragmentSrc); Shader.call(this, program, uniforms); /** * The padding of the filter. Some filters require extra space to breath such as a blur. * Increasing this will add extra width and height to the bounds of the object that the * filter is applied to. * * @member {number} */ this.padding = 0; /** * The resolution of the filter. Setting this to be lower will lower the quality but * increase the performance of the filter. * * @member {number} */ this.resolution = settings.settings.FILTER_RESOLUTION; /** * If enabled is true the filter is applied, if false it will not. * * @member {boolean} */ this.enabled = true; /** * If enabled, PixiJS will fit the filter area into boundaries for better performance. * Switch it off if it does not work for specific shader. * * @member {boolean} */ this.autoFit = true; /** * Legacy filters use position and uvs from attributes * @member {boolean} * @readonly */ this.legacy = !!this.program.attributeData.aTextureCoord; /** * The WebGL state the filter requires to render * @member {PIXI.State} */ this.state = new State(); } if ( Shader ) Filter.__proto__ = Shader; Filter.prototype = Object.create( Shader && Shader.prototype ); Filter.prototype.constructor = Filter; var prototypeAccessors = { blendMode: { configurable: true } }; var staticAccessors = { defaultVertexSrc: { configurable: true },defaultFragmentSrc: { configurable: true } }; /** * Applies the filter * * @param {PIXI.systems.FilterSystem} filterManager - The renderer to retrieve the filter from * @param {PIXI.RenderTexture} input - The input render target. * @param {PIXI.RenderTexture} output - The target to output to. * @param {boolean} clear - Should the output be cleared before rendering to it * @param {object} [currentState] - It's current state of filter. * There are some useful properties in the currentState : * target, filters, sourceFrame, destinationFrame, renderTarget, resolution */ Filter.prototype.apply = function apply (filterManager, input, output, clear, currentState) { // do as you please! filterManager.applyFilter(this, input, output, clear, currentState); // or just do a regular render.. }; /** * Sets the blendmode of the filter * * @member {number} * @default PIXI.BLEND_MODES.NORMAL */ prototypeAccessors.blendMode.get = function () { return this.state.blendMode; }; prototypeAccessors.blendMode.set = function (value) // eslint-disable-line require-jsdoc { this.state.blendMode = value; }; /** * The default vertex shader source * * @static * @type {string} * @constant */ staticAccessors.defaultVertexSrc.get = function () { return defaultVertex$1; }; /** * The default fragment shader source * * @static * @type {string} * @constant */ staticAccessors.defaultFragmentSrc.get = function () { return defaultFragment$1; }; Object.defineProperties( Filter.prototype, prototypeAccessors ); Object.defineProperties( Filter, staticAccessors ); return Filter; }(Shader)); /** * Used for caching shader IDs * * @static * @type {object} * @protected */ Filter.SOURCE_KEY_MAP = {}; var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n"; var fragment = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n"; var tempMat = new math.Matrix(); /** * Class controls uv mapping from Texture normal space to BaseTexture normal space. * * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite. * * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture. * If you want to add support for texture region of certain feature or filter, that's what you're looking for. * * Takes track of Texture changes through `_lastTextureID` private field. * Use `update()` method call to track it from outside. * * @see PIXI.Texture * @see PIXI.Mesh * @see PIXI.TilingSprite * @class * @memberof PIXI */ var TextureMatrix = function TextureMatrix(texture, clampMargin) { this._texture = texture; /** * Matrix operation that converts texture region coords to texture coords * @member {PIXI.Matrix} * @readonly */ this.mapCoord = new math.Matrix(); /** * Clamp region for normalized coords, left-top pixel center in xy , bottom-right in zw. * Calculated based on clampOffset. * @member {Float32Array} * @readonly */ this.uClampFrame = new Float32Array(4); /** * Normalized clamp offset. * Calculated based on clampOffset. * @member {Float32Array} * @readonly */ this.uClampOffset = new Float32Array(2); /** * Tracks Texture frame changes * @member {number} * @protected */ this._updateID = -1; /** * Changes frame clamping * Works with TilingSprite and Mesh * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders * * @default 0 * @member {number} */ this.clampOffset = 0; /** * Changes frame clamping * Works with TilingSprite and Mesh * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas * * @default 0.5 * @member {number} */ this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin; /** * If texture size is the same as baseTexture * @member {boolean} * @default false * @readonly */ this.isSimple = false; }; var prototypeAccessors$4 = { texture: { configurable: true } }; /** * texture property * @member {PIXI.Texture} */ prototypeAccessors$4.texture.get = function () { return this._texture; }; prototypeAccessors$4.texture.set = function (value) // eslint-disable-line require-jsdoc { this._texture = value; this._updateID = -1; }; /** * Multiplies uvs array to transform * @param {Float32Array} uvs mesh uvs * @param {Float32Array} [out=uvs] output * @returns {Float32Array} output */ TextureMatrix.prototype.multiplyUvs = function multiplyUvs (uvs, out) { if (out === undefined) { out = uvs; } var mat = this.mapCoord; for (var i = 0; i < uvs.length; i += 2) { var x = uvs[i]; var y = uvs[i + 1]; out[i] = (x * mat.a) + (y * mat.c) + mat.tx; out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty; } return out; }; /** * updates matrices if texture was changed * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case * @returns {boolean} whether or not it was updated */ TextureMatrix.prototype.update = function update (forceUpdate) { var tex = this._texture; if (!tex || !tex.valid) { return false; } if (!forceUpdate && this._updateID === tex._updateID) { return false; } this._updateID = tex._updateID; var uvs = tex._uvs; this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); var orig = tex.orig; var trim = tex.trim; if (trim) { tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); this.mapCoord.append(tempMat); } var texBase = tex.baseTexture; var frame = this.uClampFrame; var margin = this.clampMargin / texBase.resolution; var offset = this.clampOffset; frame[0] = (tex._frame.x + margin + offset) / texBase.width; frame[1] = (tex._frame.y + margin + offset) / texBase.height; frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; this.uClampOffset[0] = offset / texBase.realWidth; this.uClampOffset[1] = offset / texBase.realHeight; this.isSimple = tex._frame.width === texBase.width && tex._frame.height === texBase.height && tex.rotate === 0; return true; }; Object.defineProperties( TextureMatrix.prototype, prototypeAccessors$4 ); /** * This handles a Sprite acting as a mask, as opposed to a Graphic. * * WebGL only. * * @class * @extends PIXI.Filter * @memberof PIXI */ var SpriteMaskFilter = /*@__PURE__*/(function (Filter) { function SpriteMaskFilter(sprite) { var maskMatrix = new math.Matrix(); Filter.call(this, vertex, fragment); sprite.renderable = false; /** * Sprite mask * @member {PIXI.Sprite} */ this.maskSprite = sprite; /** * Mask matrix * @member {PIXI.Matrix} */ this.maskMatrix = maskMatrix; } if ( Filter ) SpriteMaskFilter.__proto__ = Filter; SpriteMaskFilter.prototype = Object.create( Filter && Filter.prototype ); SpriteMaskFilter.prototype.constructor = SpriteMaskFilter; /** * Applies the filter * * @param {PIXI.systems.FilterSystem} filterManager - The renderer to retrieve the filter from * @param {PIXI.RenderTexture} input - The input render target. * @param {PIXI.RenderTexture} output - The target to output to. * @param {boolean} clear - Should the output be cleared before rendering to it. */ SpriteMaskFilter.prototype.apply = function apply (filterManager, input, output, clear) { var maskSprite = this.maskSprite; var tex = this.maskSprite.texture; if (!tex.valid) { return; } if (!tex.transform) { // margin = 0.0, let it bleed a bit, shader code becomes easier // assuming that atlas textures were made with 1-pixel padding tex.transform = new TextureMatrix(tex, 0.0); } tex.transform.update(); this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0; this.uniforms.mask = tex; // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend` this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite) .prepend(tex.transform.mapCoord); this.uniforms.alpha = maskSprite.worldAlpha; this.uniforms.maskClamp = tex.transform.uClampFrame; filterManager.applyFilter(this, input, output, clear); }; return SpriteMaskFilter; }(Filter)); /** * System plugin to the renderer to manage masks. * * @class * @extends PIXI.System * @memberof PIXI.systems */ var MaskSystem = /*@__PURE__*/(function (System) { function MaskSystem(renderer) { System.call(this, renderer); /** * Target to mask * @member {PIXI.DisplayObject} * @readonly */ this.scissorRenderTarget = null; /** * Enable scissor * @member {boolean} * @readonly */ this.enableScissor = false; /** * Pool of used sprite mask filters * @member {PIXI.SpriteMaskFilter[]} * @readonly */ this.alphaMaskPool = []; /** * Pool of mask data * @member {PIXI.MaskData[]} * @readonly */ this.maskDataPool = []; this.maskStack = []; /** * Current index of alpha mask pool * @member {number} * @default 0 * @readonly */ this.alphaMaskIndex = 0; } if ( System ) MaskSystem.__proto__ = System; MaskSystem.prototype = Object.create( System && System.prototype ); MaskSystem.prototype.constructor = MaskSystem; /** * Changes the mask stack that is used by this System. * * @param {PIXI.MaskData[]} maskStack - The mask stack */ MaskSystem.prototype.setMaskStack = function setMaskStack (maskStack) { this.maskStack = maskStack; this.renderer.scissor.setMaskStack(maskStack); this.renderer.stencil.setMaskStack(maskStack); }; /** * Applies the Mask and adds it to the current filter stack. * Renderer batch must be flushed beforehand. * * @param {PIXI.DisplayObject} target - Display Object to push the mask to * @param {PIXI.MaskData|PIXI.Sprite|PIXI.Graphics|PIXI.DisplayObject} maskData - The masking data. */ MaskSystem.prototype.push = function push (target, maskData) { if (!maskData.isMaskData) { var d = this.maskDataPool.pop() || new MaskData(); d.pooled = true; d.maskObject = maskData; maskData = d; } if (maskData.autoDetect) { this.detect(maskData); } maskData.copyCountersOrReset(this.maskStack[this.maskStack.length - 1]); maskData._target = target; switch (maskData.type) { case constants.MASK_TYPES.SCISSOR: this.maskStack.push(maskData); this.renderer.scissor.push(maskData); break; case constants.MASK_TYPES.STENCIL: this.maskStack.push(maskData); this.renderer.stencil.push(maskData); break; case constants.MASK_TYPES.SPRITE: maskData.copyCountersOrReset(null); this.pushSpriteMask(maskData); this.maskStack.push(maskData); break; default: break; } }; /** * Removes the last mask from the mask stack and doesn't return it. * Renderer batch must be flushed beforehand. * * @param {PIXI.DisplayObject} target - Display Object to pop the mask from */ MaskSystem.prototype.pop = function pop (target) { var maskData = this.maskStack.pop(); if (!maskData || maskData._target !== target) { // TODO: add an assert when we have it return; } switch (maskData.type) { case constants.MASK_TYPES.SCISSOR: this.renderer.scissor.pop(); break; case constants.MASK_TYPES.STENCIL: this.renderer.stencil.pop(maskData.maskObject); break; case constants.MASK_TYPES.SPRITE: this.popSpriteMask(); break; default: break; } maskData.reset(); if (maskData.pooled) { this.maskDataPool.push(maskData); } }; /** * Sets type of MaskData based on its maskObject * @param {PIXI.MaskData} maskData */ MaskSystem.prototype.detect = function detect (maskData) { var maskObject = maskData.maskObject; if (maskObject.isSprite) { maskData.type = constants.MASK_TYPES.SPRITE; return; } maskData.type = constants.MASK_TYPES.STENCIL; // detect scissor in graphics if (this.enableScissor && maskObject.isFastRect && maskObject.isFastRect()) { var matrix = maskObject.worldTransform; // TODO: move the check to the matrix itself // we are checking that its orthogonal and x rotation is 0 90 180 or 270 var rotX = Math.atan2(matrix.b, matrix.a); var rotXY = Math.atan2(matrix.d, matrix.c); // use the nearest degree to 0.01 rotX = Math.round(rotX * (180 / Math.PI) * 100); rotXY = Math.round(rotXY * (180 / Math.PI) * 100) - rotX; rotX = ((rotX % 9000) + 9000) % 9000; rotXY = ((rotXY % 18000) + 18000) % 18000; if (rotX === 0 && rotXY === 9000) { maskData.type = constants.MASK_TYPES.SCISSOR; } } }; /** * Applies the Mask and adds it to the current filter stack. * * @param {PIXI.MaskData} maskData - Sprite to be used as the mask */ MaskSystem.prototype.pushSpriteMask = function pushSpriteMask (maskData) { var maskObject = maskData.maskObject; var target = maskData._target; var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; if (!alphaMaskFilter) { alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter(maskObject)]; } alphaMaskFilter[0].resolution = this.renderer.resolution; alphaMaskFilter[0].maskSprite = maskObject; var stashFilterArea = target.filterArea; target.filterArea = maskObject.getBounds(true); this.renderer.filter.push(target, alphaMaskFilter); target.filterArea = stashFilterArea; this.alphaMaskIndex++; }; /** * Removes the last filter from the filter stack and doesn't return it. */ MaskSystem.prototype.popSpriteMask = function popSpriteMask () { this.renderer.filter.pop(); this.alphaMaskIndex--; }; return MaskSystem; }(System)); /** * System plugin to the renderer to manage masks of certain type * * @class * @extends PIXI.System * @memberof PIXI.systems */ var AbstractMaskSystem = /*@__PURE__*/(function (System) { function AbstractMaskSystem(renderer) { System.call(this, renderer); /** * The mask stack * @member {PIXI.MaskData[]} */ this.maskStack = []; /** * Constant for gl.enable * @member {number} * @private */ this.glConst = 0; } if ( System ) AbstractMaskSystem.__proto__ = System; AbstractMaskSystem.prototype = Object.create( System && System.prototype ); AbstractMaskSystem.prototype.constructor = AbstractMaskSystem; /** * gets count of masks of certain type * @returns {number} */ AbstractMaskSystem.prototype.getStackLength = function getStackLength () { return this.maskStack.length; }; /** * Changes the mask stack that is used by this System. * * @param {PIXI.MaskData[]} maskStack - The mask stack */ AbstractMaskSystem.prototype.setMaskStack = function setMaskStack (maskStack) { var ref = this.renderer; var gl = ref.gl; var curStackLen = this.getStackLength(); this.maskStack = maskStack; var newStackLen = this.getStackLength(); if (newStackLen !== curStackLen) { if (newStackLen === 0) { gl.disable(this.glConst); } else { gl.enable(this.glConst); this._useCurrent(); } } }; /** * Setup renderer to use the current mask data. * @private */ AbstractMaskSystem.prototype._useCurrent = function _useCurrent () { // OVERWRITE; }; /** * Destroys the mask stack. * */ AbstractMaskSystem.prototype.destroy = function destroy () { System.prototype.destroy.call(this, this); this.maskStack = null; }; return AbstractMaskSystem; }(System)); /** * System plugin to the renderer to manage scissor rects (used for masks). * * @class * @extends PIXI.System * @memberof PIXI.systems */ var ScissorSystem = /*@__PURE__*/(function (AbstractMaskSystem) { function ScissorSystem(renderer) { AbstractMaskSystem.call(this, renderer); this.glConst = WebGLRenderingContext.SCISSOR_TEST; } if ( AbstractMaskSystem ) ScissorSystem.__proto__ = AbstractMaskSystem; ScissorSystem.prototype = Object.create( AbstractMaskSystem && AbstractMaskSystem.prototype ); ScissorSystem.prototype.constructor = ScissorSystem; ScissorSystem.prototype.getStackLength = function getStackLength () { var maskData = this.maskStack[this.maskStack.length - 1]; if (maskData) { return maskData._scissorCounter; } return 0; }; /** * Applies the Mask and adds it to the current stencil stack. @alvin * * @param {PIXI.MaskData} maskData - The mask data */ ScissorSystem.prototype.push = function push (maskData) { var maskObject = maskData.maskObject; maskObject.renderable = true; var prevData = maskData._scissorRect; var bounds = maskObject.getBounds(true); var ref = this.renderer; var gl = ref.gl; maskObject.renderable = false; if (prevData) { bounds.fit(prevData); } else { gl.enable(gl.SCISSOR_TEST); } maskData._scissorCounter++; maskData._scissorRect = bounds; this._useCurrent(); }; /** * Pops scissor mask. MaskData is already removed from stack */ ScissorSystem.prototype.pop = function pop () { var ref = this.renderer; var gl = ref.gl; if (this.getStackLength() > 0) { this._useCurrent(); } else { gl.disable(gl.SCISSOR_TEST); } }; /** * Setup renderer to use the current scissor data. * @private */ ScissorSystem.prototype._useCurrent = function _useCurrent () { var rect = this.maskStack[this.maskStack.length - 1]._scissorRect; var rt = this.renderer.renderTexture.current; var ref = this.renderer.projection; var transform = ref.transform; var sourceFrame = ref.sourceFrame; var destinationFrame = ref.destinationFrame; var resolution = rt ? rt.resolution : this.renderer.resolution; var x = ((rect.x - sourceFrame.x) * resolution) + destinationFrame.x; var y = ((rect.y - sourceFrame.y) * resolution) + destinationFrame.y; var width = rect.width * resolution; var height = rect.height * resolution; if (transform) { x += transform.tx * resolution; y += transform.ty * resolution; } if (!rt) { // flipY. In future we'll have it over renderTextures as an option y = this.renderer.height - height - y; } this.renderer.gl.scissor(x, y, width, height); }; return ScissorSystem; }(AbstractMaskSystem)); /** * System plugin to the renderer to manage stencils (used for masks). * * @class * @extends PIXI.System * @memberof PIXI.systems */ var StencilSystem = /*@__PURE__*/(function (AbstractMaskSystem) { function StencilSystem(renderer) { AbstractMaskSystem.call(this, renderer); this.glConst = WebGLRenderingContext.STENCIL_TEST; } if ( AbstractMaskSystem ) StencilSystem.__proto__ = AbstractMaskSystem; StencilSystem.prototype = Object.create( AbstractMaskSystem && AbstractMaskSystem.prototype ); StencilSystem.prototype.constructor = StencilSystem; StencilSystem.prototype.getStackLength = function getStackLength () { var maskData = this.maskStack[this.maskStack.length - 1]; if (maskData) { return maskData._stencilCounter; } return 0; }; /** * Applies the Mask and adds it to the current stencil stack. * * @param {PIXI.MaskData} maskData - The mask data */ StencilSystem.prototype.push = function push (maskData) { var maskObject = maskData.maskObject; var ref = this.renderer; var gl = ref.gl; var prevMaskCount = maskData._stencilCounter; if (prevMaskCount === 0) { // force use stencil texture in current framebuffer this.renderer.framebuffer.forceStencil(); gl.enable(gl.STENCIL_TEST); } maskData._stencilCounter++; // Increment the reference stencil value where the new mask overlaps with the old ones. gl.colorMask(false, false, false, false); gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask()); gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); maskObject.renderable = true; maskObject.render(this.renderer); this.renderer.batch.flush(); maskObject.renderable = false; this._useCurrent(); }; /** * Pops stencil mask. MaskData is already removed from stack * * @param {PIXI.DisplayObject} maskObject - object of popped mask data */ StencilSystem.prototype.pop = function pop (maskObject) { var gl = this.renderer.gl; if (this.getStackLength() === 0) { // the stack is empty! gl.disable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); gl.clearStencil(0); } else { // Decrement the reference stencil value where the popped mask overlaps with the other ones gl.colorMask(false, false, false, false); gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); maskObject.renderable = true; maskObject.render(this.renderer); this.renderer.batch.flush(); maskObject.renderable = false; this._useCurrent(); } }; /** * Setup renderer to use the current stencil data. * @private */ StencilSystem.prototype._useCurrent = function _useCurrent () { var gl = this.renderer.gl; gl.colorMask(true, true, true, true); gl.stencilFunc(gl.EQUAL, this.getStackLength(), this._getBitwiseMask()); gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); }; /** * Fill 1s equal to the number of acitve stencil masks. * @private * @return {number} The bitwise mask. */ StencilSystem.prototype._getBitwiseMask = function _getBitwiseMask () { return (1 << this.getStackLength()) - 1; }; return StencilSystem; }(AbstractMaskSystem)); /** * System plugin to the renderer to manage the projection matrix. * * @class * @extends PIXI.System * @memberof PIXI.systems */ var ProjectionSystem = /*@__PURE__*/(function (System) { function ProjectionSystem(renderer) { System.call(this, renderer); /** * Destination frame * @member {PIXI.Rectangle} * @readonly */ this.destinationFrame = null; /** * Source frame * @member {PIXI.Rectangle} * @readonly */ this.sourceFrame = null; /** * Default destination frame * @member {PIXI.Rectangle} * @readonly */ this.defaultFrame = null; /** * Project matrix * @member {PIXI.Matrix} * @readonly */ this.projectionMatrix = new math.Matrix(); /** * A transform that will be appended to the projection matrix * if null, nothing will be applied * @member {PIXI.Matrix} */ this.transform = null; } if ( System ) ProjectionSystem.__proto__ = System; ProjectionSystem.prototype = Object.create( System && System.prototype ); ProjectionSystem.prototype.constructor = ProjectionSystem; /** * Updates the projection matrix based on a projection frame (which is a rectangle) * * @param {PIXI.Rectangle} destinationFrame - The destination frame. * @param {PIXI.Rectangle} sourceFrame - The source frame. * @param {Number} resolution - Resolution * @param {boolean} root - If is root */ ProjectionSystem.prototype.update = function update (destinationFrame, sourceFrame, resolution, root) { this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root); if (this.transform) { this.projectionMatrix.append(this.transform); } var renderer = this.renderer; renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix; renderer.globalUniforms.update(); // this will work for now // but would be sweet to stick and even on the global uniforms.. if (renderer.shader.shader) { renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals); } }; /** * Updates the projection matrix based on a projection frame (which is a rectangle) * * @param {PIXI.Rectangle} destinationFrame - The destination frame. * @param {PIXI.Rectangle} sourceFrame - The source frame. * @param {Number} resolution - Resolution * @param {boolean} root - If is root */ ProjectionSystem.prototype.calculateProjection = function calculateProjection (destinationFrame, sourceFrame, resolution, root) { var pm = this.projectionMatrix; // I don't think we will need this line.. // pm.identity(); if (!root) { pm.a = (1 / destinationFrame.width * 2) * resolution; pm.d = (1 / destinationFrame.height * 2) * resolution; pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); } else { pm.a = (1 / destinationFrame.width * 2) * resolution; pm.d = (-1 / destinationFrame.height * 2) * resolution; pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = 1 - (sourceFrame.y * pm.d); } }; /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ ProjectionSystem.prototype.setTransform = function setTransform ()// matrix) { // this._activeRenderTarget.transform = matrix; }; return ProjectionSystem; }(System)); var tempRect = new math.Rectangle(); /** * System plugin to the renderer to manage render textures. * * Should be added after FramebufferSystem * * @class * @extends PIXI.System * @memberof PIXI.systems */ var RenderTextureSystem = /*@__PURE__*/(function (System) { function RenderTextureSystem(renderer) { System.call(this, renderer); /** * The clear background color as rgba * @member {number[]} */ this.clearColor = renderer._backgroundColorRgba; // TODO move this property somewhere else! /** * List of masks for the StencilSystem * @member {PIXI.Graphics[]} * @readonly */ this.defaultMaskStack = []; // empty render texture? /** * Render texture * @member {PIXI.RenderTexture} * @readonly */ this.current = null; /** * Source frame * @member {PIXI.Rectangle} * @readonly */ this.sourceFrame = new math.Rectangle(); /** * Destination frame * @member {PIXI.Rectangle} * @readonly */ this.destinationFrame = new math.Rectangle(); } if ( System ) RenderTextureSystem.__proto__ = System; RenderTextureSystem.prototype = Object.create( System && System.prototype ); RenderTextureSystem.prototype.constructor = RenderTextureSystem; /** * Bind the current render texture * @param {PIXI.RenderTexture} [renderTexture] - RenderTexture to bind, by default its `null`, the screen * @param {PIXI.Rectangle} [sourceFrame] - part of screen that is mapped to the renderTexture * @param {PIXI.Rectangle} [destinationFrame] - part of renderTexture, by default it has the same size as sourceFrame */ RenderTextureSystem.prototype.bind = function bind (renderTexture, sourceFrame, destinationFrame) { if ( renderTexture === void 0 ) renderTexture = null; this.current = renderTexture; var renderer = this.renderer; var resolution; if (renderTexture) { var baseTexture = renderTexture.baseTexture; resolution = baseTexture.resolution; if (!destinationFrame) { tempRect.width = baseTexture.realWidth; tempRect.height = baseTexture.realHeight; destinationFrame = tempRect; } if (!sourceFrame) { sourceFrame = destinationFrame; } this.renderer.framebuffer.bind(baseTexture.framebuffer, destinationFrame); this.renderer.projection.update(destinationFrame, sourceFrame, resolution, false); this.renderer.mask.setMaskStack(baseTexture.maskStack); } else { resolution = this.renderer.resolution; // TODO these validation checks happen deeper down.. // thing they can be avoided.. if (!destinationFrame) { tempRect.width = renderer.width; tempRect.height = renderer.height; destinationFrame = tempRect; } if (!sourceFrame) { sourceFrame = destinationFrame; } renderer.framebuffer.bind(null, destinationFrame); // TODO store this.. this.renderer.projection.update(destinationFrame, sourceFrame, resolution, true); this.renderer.mask.setMaskStack(this.defaultMaskStack); } this.sourceFrame.copyFrom(sourceFrame); this.destinationFrame.x = destinationFrame.x / resolution; this.destinationFrame.y = destinationFrame.y / resolution; this.destinationFrame.width = destinationFrame.width / resolution; this.destinationFrame.height = destinationFrame.height / resolution; if (sourceFrame === destinationFrame) { this.sourceFrame.copyFrom(this.destinationFrame); } }; /** * Erases the render texture and fills the drawing area with a colour * * @param {number[]} [clearColor] - The color as rgba, default to use the renderer backgroundColor * @return {PIXI.Renderer} Returns itself. */ RenderTextureSystem.prototype.clear = function clear (clearColor) { if (this.current) { clearColor = clearColor || this.current.baseTexture.clearColor; } else { clearColor = clearColor || this.clearColor; } this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); }; RenderTextureSystem.prototype.resize = function resize ()// screenWidth, screenHeight) { // resize the root only! this.bind(null); }; /** * Resets renderTexture state */ RenderTextureSystem.prototype.reset = function reset () { this.bind(null); }; return RenderTextureSystem; }(System)); /** * Helper class to create a WebGL Program * * @class * @memberof PIXI */ var GLProgram = function GLProgram(program, uniformData) { /** * The shader program * * @member {WebGLProgram} */ this.program = program; /** * holds the uniform data which contains uniform locations * and current uniform values used for caching and preventing unneeded GPU commands * @member {Object} */ this.uniformData = uniformData; /** * uniformGroups holds the various upload functions for the shader. Each uniform group * and program have a unique upload function generated. * @member {Object} */ this.uniformGroups = {}; }; /** * Destroys this program */ GLProgram.prototype.destroy = function destroy () { this.uniformData = null; this.uniformGroups = null; this.program = null; }; var UID$4 = 0; // defualt sync data so we don't create a new one each time! var defaultSyncData = { textureCount: 0 }; /** * System plugin to the renderer to manage shaders. * * @class * @memberof PIXI.systems * @extends PIXI.System */ var ShaderSystem = /*@__PURE__*/(function (System) { function ShaderSystem(renderer) { System.call(this, renderer); // Validation check that this environment support `new Function` this.systemCheck(); /** * The current WebGL rendering context * * @member {WebGLRenderingContext} */ this.gl = null; this.shader = null; this.program = null; /** * Cache to holds the generated functions. Stored against UniformObjects unique signature * @type {Object} * @private */ this.cache = {}; this.id = UID$4++; } if ( System ) ShaderSystem.__proto__ = System; ShaderSystem.prototype = Object.create( System && System.prototype ); ShaderSystem.prototype.constructor = ShaderSystem; /** * Overrideable function by `@pixi/unsafe-eval` to silence * throwing an error if platform doesn't support unsafe-evals. * * @private */ ShaderSystem.prototype.systemCheck = function systemCheck () { if (!unsafeEvalSupported()) { throw new Error('Current environment does not allow unsafe-eval, ' + 'please use @pixi/unsafe-eval module to enable support.'); } }; ShaderSystem.prototype.contextChange = function contextChange (gl) { this.gl = gl; this.reset(); }; /** * Changes the current shader to the one given in parameter * * @param {PIXI.Shader} shader - the new shader * @param {boolean} dontSync - false if the shader should automatically sync its uniforms. * @returns {PIXI.GLProgram} the glProgram that belongs to the shader. */ ShaderSystem.prototype.bind = function bind (shader, dontSync) { shader.uniforms.globals = this.renderer.globalUniforms; var program = shader.program; var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateShader(shader); this.shader = shader; // TODO - some current Pixi plugins bypass this.. so it not safe to use yet.. if (this.program !== program) { this.program = program; this.gl.useProgram(glProgram.program); } if (!dontSync) { defaultSyncData.textureCount = 0; this.syncUniformGroup(shader.uniformGroup, defaultSyncData); } return glProgram; }; /** * Uploads the uniforms values to the currently bound shader. * * @param {object} uniforms - the uniforms values that be applied to the current shader */ ShaderSystem.prototype.setUniforms = function setUniforms (uniforms) { var shader = this.shader.program; var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID]; shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer); }; /** * * syncs uniforms on the group * @param {*} group the uniform group to sync * @param {*} syncData this is data that is passed to the sync function and any nested sync functions */ ShaderSystem.prototype.syncUniformGroup = function syncUniformGroup (group, syncData) { var glProgram = this.getglProgram(); if (!group.static || group.dirtyId !== glProgram.uniformGroups[group.id]) { glProgram.uniformGroups[group.id] = group.dirtyId; this.syncUniforms(group, glProgram, syncData); } }; /** * Overrideable by the @pixi/unsafe-eval package to use static * syncUnforms instead. * * @private */ ShaderSystem.prototype.syncUniforms = function syncUniforms (group, glProgram, syncData) { var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glProgram.uniformData, group.uniforms, this.renderer, syncData); }; ShaderSystem.prototype.createSyncGroups = function createSyncGroups (group) { var id = this.getSignature(group, this.shader.program.uniformData); if (!this.cache[id]) { this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData); } group.syncUniforms[this.shader.program.id] = this.cache[id]; return group.syncUniforms[this.shader.program.id]; }; /** * Takes a uniform group and data and generates a unique signature for them. * * @param {PIXI.UniformGroup} group the uniform group to get signature of * @param {Object} uniformData uniform information generated by the shader * @returns {String} Unique signature of the uniform group * @private */ ShaderSystem.prototype.getSignature = function getSignature (group, uniformData) { var uniforms = group.uniforms; var strings = []; for (var i in uniforms) { strings.push(i); if (uniformData[i]) { strings.push(uniformData[i].type); } } return strings.join('-'); }; /** * Returns the underlying GLShade rof the currently bound shader. * This can be handy for when you to have a little more control over the setting of your uniforms. * * @return {PIXI.GLProgram} the glProgram for the currently bound Shader for this context */ ShaderSystem.prototype.getglProgram = function getglProgram () { if (this.shader) { return this.shader.program.glPrograms[this.renderer.CONTEXT_UID]; } return null; }; /** * Generates a glProgram version of the Shader provided. * * @private * @param {PIXI.Shader} shader the shader that the glProgram will be based on. * @return {PIXI.GLProgram} A shiny new glProgram! */ ShaderSystem.prototype.generateShader = function generateShader (shader) { var gl = this.gl; var program = shader.program; var attribMap = {}; for (var i in program.attributeData) { attribMap[i] = program.attributeData[i].location; } var shaderProgram = compileProgram(gl, program.vertexSrc, program.fragmentSrc, attribMap); var uniformData = {}; for (var i$1 in program.uniformData) { var data = program.uniformData[i$1]; uniformData[i$1] = { location: gl.getUniformLocation(shaderProgram, i$1), value: defaultValue(data.type, data.size), }; } var glProgram = new GLProgram(shaderProgram, uniformData); program.glPrograms[this.renderer.CONTEXT_UID] = glProgram; return glProgram; }; /** * Resets ShaderSystem state, does not affect WebGL state */ ShaderSystem.prototype.reset = function reset () { this.program = null; this.shader = null; }; /** * Destroys this System and removes all its textures */ ShaderSystem.prototype.destroy = function destroy () { // TODO implement destroy method for ShaderSystem this.destroyed = true; }; return ShaderSystem; }(System)); /** * Maps gl blend combinations to WebGL. * * @memberof PIXI * @function mapWebGLBlendModesToPixi * @private * @param {WebGLRenderingContext} gl - The rendering context. * @param {number[][]} [array=[]] - The array to output into. * @return {number[][]} Mapped modes. */ function mapWebGLBlendModesToPixi(gl, array) { if ( array === void 0 ) array = []; // TODO - premultiply alpha would be different. // add a boolean for that! array[constants.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.ADD] = [gl.ONE, gl.ONE]; array[constants.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.NONE] = [0, 0]; // not-premultiplied blend modes array[constants.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE]; array[constants.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; // composite operations array[constants.BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO]; array[constants.BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO]; array[constants.BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE]; array[constants.BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA]; array[constants.BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA]; array[constants.BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA]; array[constants.BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; // SUBTRACT from flash array[constants.BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD]; return array; } var BLEND$1 = 0; var OFFSET$1 = 1; var CULLING$1 = 2; var DEPTH_TEST$1 = 3; var WINDING$1 = 4; /** * System plugin to the renderer to manage WebGL state machines. * * @class * @extends PIXI.System * @memberof PIXI.systems */ var StateSystem = /*@__PURE__*/(function (System) { function StateSystem(renderer) { System.call(this, renderer); /** * GL context * @member {WebGLRenderingContext} * @readonly */ this.gl = null; /** * State ID * @member {number} * @readonly */ this.stateId = 0; /** * Polygon offset * @member {number} * @readonly */ this.polygonOffset = 0; /** * Blend mode * @member {number} * @default PIXI.BLEND_MODES.NONE * @readonly */ this.blendMode = constants.BLEND_MODES.NONE; /** * Whether current blend equation is different * @member {boolean} * @protected */ this._blendEq = false; /** * Collection of calls * @member {function[]} * @readonly */ this.map = []; // map functions for when we set state.. this.map[BLEND$1] = this.setBlend; this.map[OFFSET$1] = this.setOffset; this.map[CULLING$1] = this.setCullFace; this.map[DEPTH_TEST$1] = this.setDepthTest; this.map[WINDING$1] = this.setFrontFace; /** * Collection of check calls * @member {function[]} * @readonly */ this.checks = []; /** * Default WebGL State * @member {PIXI.State} * @readonly */ this.defaultState = new State(); this.defaultState.blend = true; this.defaultState.depth = true; } if ( System ) StateSystem.__proto__ = System; StateSystem.prototype = Object.create( System && System.prototype ); StateSystem.prototype.constructor = StateSystem; StateSystem.prototype.contextChange = function contextChange (gl) { this.gl = gl; this.blendModes = mapWebGLBlendModesToPixi(gl); this.set(this.defaultState); this.reset(); }; /** * Sets the current state * * @param {*} state - The state to set. */ StateSystem.prototype.set = function set (state) { state = state || this.defaultState; // TODO maybe to an object check? ( this.state === state )? if (this.stateId !== state.data) { var diff = this.stateId ^ state.data; var i = 0; // order from least to most common while (diff) { if (diff & 1) { // state change! this.map[i].call(this, !!(state.data & (1 << i))); } diff = diff >> 1; i++; } this.stateId = state.data; } // based on the above settings we check for specific modes.. // for example if blend is active we check and set the blend modes // or of polygon offset is active we check the poly depth. for (var i$1 = 0; i$1 < this.checks.length; i$1++) { this.checks[i$1](this, state); } }; /** * Sets the state, when previous state is unknown * * @param {*} state - The state to set */ StateSystem.prototype.forceState = function forceState (state) { state = state || this.defaultState; for (var i = 0; i < this.map.length; i++) { this.map[i].call(this, !!(state.data & (1 << i))); } for (var i$1 = 0; i$1 < this.checks.length; i$1++) { this.checks[i$1](this, state); } this.stateId = state.data; }; /** * Enables or disabled blending. * * @param {boolean} value - Turn on or off webgl blending. */ StateSystem.prototype.setBlend = function setBlend (value) { this.updateCheck(StateSystem.checkBlendMode, value); this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); }; /** * Enables or disable polygon offset fill * * @param {boolean} value - Turn on or off webgl polygon offset testing. */ StateSystem.prototype.setOffset = function setOffset (value) { this.updateCheck(StateSystem.checkPolygonOffset, value); this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL); }; /** * Sets whether to enable or disable depth test. * * @param {boolean} value - Turn on or off webgl depth testing. */ StateSystem.prototype.setDepthTest = function setDepthTest (value) { this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); }; /** * Sets whether to enable or disable cull face. * * @param {boolean} value - Turn on or off webgl cull face. */ StateSystem.prototype.setCullFace = function setCullFace (value) { this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); }; /** * Sets the gl front face. * * @param {boolean} value - true is clockwise and false is counter-clockwise */ StateSystem.prototype.setFrontFace = function setFrontFace (value) { this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); }; /** * Sets the blend mode. * * @param {number} value - The blend mode to set to. */ StateSystem.prototype.setBlendMode = function setBlendMode (value) { if (value === this.blendMode) { return; } this.blendMode = value; var mode = this.blendModes[value]; var gl = this.gl; if (mode.length === 2) { gl.blendFunc(mode[0], mode[1]); } else { gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); } if (mode.length === 6) { this._blendEq = true; gl.blendEquationSeparate(mode[4], mode[5]); } else if (this._blendEq) { this._blendEq = false; gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); } }; /** * Sets the polygon offset. * * @param {number} value - the polygon offset * @param {number} scale - the polygon offset scale */ StateSystem.prototype.setPolygonOffset = function setPolygonOffset (value, scale) { this.gl.polygonOffset(value, scale); }; // used /** * Resets all the logic and disables the vaos */ StateSystem.prototype.reset = function reset () { this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); this.forceState(0); this._blendEq = true; this.blendMode = -1; this.setBlendMode(0); }; /** * checks to see which updates should be checked based on which settings have been activated. * For example, if blend is enabled then we should check the blend modes each time the state is changed * or if polygon fill is activated then we need to check if the polygon offset changes. * The idea is that we only check what we have too. * * @param {Function} func the checking function to add or remove * @param {boolean} value should the check function be added or removed. */ StateSystem.prototype.updateCheck = function updateCheck (func, value) { var index = this.checks.indexOf(func); if (value && index === -1) { this.checks.push(func); } else if (!value && index !== -1) { this.checks.splice(index, 1); } }; /** * A private little wrapper function that we call to check the blend mode. * * @static * @private * @param {PIXI.StateSystem} System the System to perform the state check on * @param {PIXI.State} state the state that the blendMode will pulled from */ StateSystem.checkBlendMode = function checkBlendMode (system, state) { system.setBlendMode(state.blendMode); }; /** * A private little wrapper function that we call to check the polygon offset. * * @static * @private * @param {PIXI.StateSystem} System the System to perform the state check on * @param {PIXI.State} state the state that the blendMode will pulled from */ StateSystem.checkPolygonOffset = function checkPolygonOffset (system, state) { system.setPolygonOffset(state.polygonOffset, 0); }; return StateSystem; }(System)); /** * System plugin to the renderer to manage texture garbage collection on the GPU, * ensuring that it does not get clogged up with textures that are no longer being used. * * @class * @memberof PIXI.systems * @extends PIXI.System */ var TextureGCSystem = /*@__PURE__*/(function (System) { function TextureGCSystem(renderer) { System.call(this, renderer); /** * Count * @member {number} * @readonly */ this.count = 0; /** * Check count * @member {number} * @readonly */ this.checkCount = 0; /** * Maximum idle time, in seconds * @member {number} * @see PIXI.settings.GC_MAX_IDLE */ this.maxIdle = settings.settings.GC_MAX_IDLE; /** * Maximum number of item to check * @member {number} * @see PIXI.settings.GC_MAX_CHECK_COUNT */ this.checkCountMax = settings.settings.GC_MAX_CHECK_COUNT; /** * Current garabage collection mode * @member {PIXI.GC_MODES} * @see PIXI.settings.GC_MODE */ this.mode = settings.settings.GC_MODE; } if ( System ) TextureGCSystem.__proto__ = System; TextureGCSystem.prototype = Object.create( System && System.prototype ); TextureGCSystem.prototype.constructor = TextureGCSystem; /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU */ TextureGCSystem.prototype.postrender = function postrender () { if (!this.renderer.renderingToScreen) { return; } this.count++; if (this.mode === constants.GC_MODES.MANUAL) { return; } this.checkCount++; if (this.checkCount > this.checkCountMax) { this.checkCount = 0; this.run(); } }; /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU */ TextureGCSystem.prototype.run = function run () { var tm = this.renderer.texture; var managedTextures = tm.managedTextures; var wasRemoved = false; for (var i = 0; i < managedTextures.length; i++) { var texture = managedTextures[i]; // only supports non generated textures at the moment! if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) { tm.destroyTexture(texture, true); managedTextures[i] = null; wasRemoved = true; } } if (wasRemoved) { var j = 0; for (var i$1 = 0; i$1 < managedTextures.length; i$1++) { if (managedTextures[i$1] !== null) { managedTextures[j++] = managedTextures[i$1]; } } managedTextures.length = j; } }; /** * Removes all the textures within the specified displayObject and its children from the GPU * * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. */ TextureGCSystem.prototype.unload = function unload (displayObject) { var tm = this.renderer.textureSystem; // only destroy non generated textures if (displayObject._texture && displayObject._texture._glRenderTargets) { tm.destroyTexture(displayObject._texture); } for (var i = displayObject.children.length - 1; i >= 0; i--) { this.unload(displayObject.children[i]); } }; return TextureGCSystem; }(System)); /** * Internal texture for WebGL context * @class * @memberof PIXI */ var GLTexture = function GLTexture(texture) { /** * The WebGL texture * @member {WebGLTexture} */ this.texture = texture; /** * Width of texture that was used in texImage2D * @member {number} */ this.width = -1; /** * Height of texture that was used in texImage2D * @member {number} */ this.height = -1; /** * Texture contents dirty flag * @member {number} */ this.dirtyId = -1; /** * Texture style dirty flag * @member {number} */ this.dirtyStyleId = -1; /** * Whether mip levels has to be generated * @member {boolean} */ this.mipmap = false; /** * WrapMode copied from baseTexture * @member {number} */ this.wrapMode = 33071; /** * Type copied from baseTexture * @member {number} */ this.type = 6408; /** * Type copied from baseTexture * @member {number} */ this.internalFormat = 5121; }; /** * System plugin to the renderer to manage textures. * * @class * @extends PIXI.System * @memberof PIXI.systems */ var TextureSystem = /*@__PURE__*/(function (System) { function TextureSystem(renderer) { System.call(this, renderer); // TODO set to max textures... /** * Bound textures * @member {PIXI.BaseTexture[]} * @readonly */ this.boundTextures = []; /** * Current location * @member {number} * @readonly */ this.currentLocation = -1; /** * List of managed textures * @member {PIXI.BaseTexture[]} * @readonly */ this.managedTextures = []; /** * Did someone temper with textures state? We'll overwrite them when we need to unbind something. * @member {boolean} * @private */ this._unknownBoundTextures = false; /** * BaseTexture value that shows that we don't know what is bound * @member {PIXI.BaseTexture} * @readonly */ this.unknownTexture = new BaseTexture(); } if ( System ) TextureSystem.__proto__ = System; TextureSystem.prototype = Object.create( System && System.prototype ); TextureSystem.prototype.constructor = TextureSystem; /** * Sets up the renderer context and necessary buffers. */ TextureSystem.prototype.contextChange = function contextChange () { var gl = this.gl = this.renderer.gl; this.CONTEXT_UID = this.renderer.CONTEXT_UID; this.webGLVersion = this.renderer.context.webGLVersion; var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); this.boundTextures.length = maxTextures; for (var i = 0; i < maxTextures; i++) { this.boundTextures[i] = null; } // TODO move this.. to a nice make empty textures class.. this.emptyTextures = {}; var emptyTexture2D = new GLTexture(gl.createTexture()); gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D; this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture()); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); for (var i$1 = 0; i$1 < 6; i$1++) { gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i$1, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); for (var i$2 = 0; i$2 < this.boundTextures.length; i$2++) { this.bind(null, i$2); } }; /** * Bind a texture to a specific location * * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)` * * @param {PIXI.Texture|PIXI.BaseTexture} texture - Texture to bind * @param {number} [location=0] - Location to bind at */ TextureSystem.prototype.bind = function bind (texture, location) { if ( location === void 0 ) location = 0; var ref = this; var gl = ref.gl; if (texture) { texture = texture.baseTexture || texture; if (texture.valid) { texture.touched = this.renderer.textureGC.count; var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); if (this.boundTextures[location] !== texture) { if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } gl.bindTexture(texture.target, glTexture.texture); } if (glTexture.dirtyId !== texture.dirtyId) { if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } this.updateTexture(texture); } this.boundTextures[location] = texture; } } else { if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture); this.boundTextures[location] = null; } }; /** * Resets texture location and bound textures * * Actual `bind(null, i)` calls will be performed at next `unbind()` call */ TextureSystem.prototype.reset = function reset () { this._unknownBoundTextures = true; this.currentLocation = -1; for (var i = 0; i < this.boundTextures.length; i++) { this.boundTextures[i] = this.unknownTexture; } }; /** * Unbind a texture * @param {PIXI.Texture|PIXI.BaseTexture} texture - Texture to bind */ TextureSystem.prototype.unbind = function unbind (texture) { var ref = this; var gl = ref.gl; var boundTextures = ref.boundTextures; if (this._unknownBoundTextures) { this._unknownBoundTextures = false; // someone changed webGL state, // we have to be sure that our texture does not appear in multi-texture renderer samplers for (var i = 0; i < boundTextures.length; i++) { if (boundTextures[i] === this.unknownTexture) { this.bind(null, i); } } } for (var i$1 = 0; i$1 < boundTextures.length; i$1++) { if (boundTextures[i$1] === texture) { if (this.currentLocation !== i$1) { gl.activeTexture(gl.TEXTURE0 + i$1); this.currentLocation = i$1; } gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[texture.target].texture); boundTextures[i$1] = null; } } }; /** * Initialize a texture * * @private * @param {PIXI.BaseTexture} texture - Texture to initialize */ TextureSystem.prototype.initTexture = function initTexture (texture) { var glTexture = new GLTexture(this.gl.createTexture()); // guarantee an update.. glTexture.dirtyId = -1; texture._glTextures[this.CONTEXT_UID] = glTexture; this.managedTextures.push(texture); texture.on('dispose', this.destroyTexture, this); return glTexture; }; TextureSystem.prototype.initTextureType = function initTextureType (texture, glTexture) { glTexture.internalFormat = texture.format; glTexture.type = texture.type; if (this.webGLVersion !== 2) { return; } var gl = this.renderer.gl; if (texture.type === gl.FLOAT && texture.format === gl.RGBA) { glTexture.internalFormat = gl.RGBA32F; } // that's WebGL1 HALF_FLOAT_OES // we have to convert it to WebGL HALF_FLOAT if (texture.type === constants.TYPES.HALF_FLOAT) { glTexture.type = gl.HALF_FLOAT; } if (glTexture.type === gl.HALF_FLOAT && texture.format === gl.RGBA) { glTexture.internalFormat = gl.RGBA16F; } }; /** * Update a texture * * @private * @param {PIXI.BaseTexture} texture - Texture to initialize */ TextureSystem.prototype.updateTexture = function updateTexture (texture) { var glTexture = texture._glTextures[this.CONTEXT_UID]; if (!glTexture) { return; } var renderer = this.renderer; this.initTextureType(texture, glTexture); if (texture.resource && texture.resource.upload(renderer, texture, glTexture)) ; else { // default, renderTexture-like logic var width = texture.realWidth; var height = texture.realHeight; var gl = renderer.gl; if (glTexture.width !== width || glTexture.height !== height || glTexture.dirtyId < 0) { glTexture.width = width; glTexture.height = height; gl.texImage2D(texture.target, 0, glTexture.internalFormat, width, height, 0, texture.format, glTexture.type, null); } } // lets only update what changes.. if (texture.dirtyStyleId !== glTexture.dirtyStyleId) { this.updateTextureStyle(texture); } glTexture.dirtyId = texture.dirtyId; }; /** * Deletes the texture from WebGL * * @private * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. */ TextureSystem.prototype.destroyTexture = function destroyTexture (texture, skipRemove) { var ref = this; var gl = ref.gl; texture = texture.baseTexture || texture; if (texture._glTextures[this.CONTEXT_UID]) { this.unbind(texture); gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture); texture.off('dispose', this.destroyTexture, this); delete texture._glTextures[this.CONTEXT_UID]; if (!skipRemove) { var i = this.managedTextures.indexOf(texture); if (i !== -1) { utils.removeItems(this.managedTextures, i, 1); } } } }; /** * Update texture style such as mipmap flag * * @private * @param {PIXI.BaseTexture} texture - Texture to update */ TextureSystem.prototype.updateTextureStyle = function updateTextureStyle (texture) { var glTexture = texture._glTextures[this.CONTEXT_UID]; if (!glTexture) { return; } if ((texture.mipmap === constants.MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) { glTexture.mipmap = 0; } else { glTexture.mipmap = texture.mipmap >= 1; } if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) { glTexture.wrapMode = constants.WRAP_MODES.CLAMP; } else { glTexture.wrapMode = texture.wrapMode; } if (texture.resource && texture.resource.style(this.renderer, texture, glTexture)) ; else { this.setStyle(texture, glTexture); } glTexture.dirtyStyleId = texture.dirtyStyleId; }; /** * Set style for texture * * @private * @param {PIXI.BaseTexture} texture - Texture to update * @param {PIXI.GLTexture} glTexture */ TextureSystem.prototype.setStyle = function setStyle (texture, glTexture) { var gl = this.gl; if (glTexture.mipmap) { gl.generateMipmap(texture.target); } gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode); if (glTexture.mipmap) { /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); /* eslint-disable max-len */ var anisotropicExt = this.renderer.context.extensions.anisotropicFiltering; if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === constants.SCALE_MODES.LINEAR) { var level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT)); gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level); } } else { gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); }; return TextureSystem; }(System)); /** * Systems are individual components to the Renderer pipeline. * @namespace PIXI.systems */ var systems = ({ FilterSystem: FilterSystem, BatchSystem: BatchSystem, ContextSystem: ContextSystem, FramebufferSystem: FramebufferSystem, GeometrySystem: GeometrySystem, MaskSystem: MaskSystem, ScissorSystem: ScissorSystem, StencilSystem: StencilSystem, ProjectionSystem: ProjectionSystem, RenderTextureSystem: RenderTextureSystem, ShaderSystem: ShaderSystem, StateSystem: StateSystem, TextureGCSystem: TextureGCSystem, TextureSystem: TextureSystem }); var tempMatrix = new math.Matrix(); /** * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene. * * @abstract * @class * @extends PIXI.utils.EventEmitter * @memberof PIXI */ var AbstractRenderer = /*@__PURE__*/(function (EventEmitter) { function AbstractRenderer(system, options) { EventEmitter.call(this); // Add the default render options options = Object.assign({}, settings.settings.RENDER_OPTIONS, options); // Deprecation notice for renderer roundPixels option if (options.roundPixels) { settings.settings.ROUND_PIXELS = options.roundPixels; utils.deprecation('5.0.0', 'Renderer roundPixels option is deprecated, please use PIXI.settings.ROUND_PIXELS', 2); } /** * The supplied constructor options. * * @member {Object} * @readOnly */ this.options = options; /** * The type of the renderer. * * @member {number} * @default PIXI.RENDERER_TYPE.UNKNOWN * @see PIXI.RENDERER_TYPE */ this.type = constants.RENDERER_TYPE.UNKNOWN; /** * Measurements of the screen. (0, 0, screenWidth, screenHeight). * * Its safe to use as filterArea or hitArea for the whole stage. * * @member {PIXI.Rectangle} */ this.screen = new math.Rectangle(0, 0, options.width, options.height); /** * The canvas element that everything is drawn to. * * @member {HTMLCanvasElement} */ this.view = options.view || document.createElement('canvas'); /** * The resolution / device pixel ratio of the renderer. * * @member {number} * @default 1 */ this.resolution = options.resolution || settings.settings.RESOLUTION; /** * Whether the render view is transparent. * * @member {boolean} */ this.transparent = options.transparent; /** * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically. * * @member {boolean} */ this.autoDensity = options.autoDensity || options.autoResize || false; // autoResize is deprecated, provides fallback support /** * The value of the preserveDrawingBuffer flag affects whether or not the contents of * the stencil buffer is retained after rendering. * * @member {boolean} */ this.preserveDrawingBuffer = options.preserveDrawingBuffer; /** * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect * to clear the canvas every frame. Disable this by setting this to false. For example, if * your game has a canvas filling background image you often don't need this set. * * @member {boolean} * @default */ this.clearBeforeRender = options.clearBeforeRender; /** * The background color as a number. * * @member {number} * @protected */ this._backgroundColor = 0x000000; /** * The background color as an [R, G, B] array. * * @member {number[]} * @protected */ this._backgroundColorRgba = [0, 0, 0, 0]; /** * The background color as a string. * * @member {string} * @protected */ this._backgroundColorString = '#000000'; this.backgroundColor = options.backgroundColor || this._backgroundColor; // run bg color setter /** * This temporary display object used as the parent of the currently being rendered item. * * @member {PIXI.DisplayObject} * @protected */ this._tempDisplayObjectParent = new display.Container(); /** * The last root object that the renderer tried to render. * * @member {PIXI.DisplayObject} * @protected */ this._lastObjectRendered = this._tempDisplayObjectParent; /** * Collection of plugins. * @readonly * @member {object} */ this.plugins = {}; } if ( EventEmitter ) AbstractRenderer.__proto__ = EventEmitter; AbstractRenderer.prototype = Object.create( EventEmitter && EventEmitter.prototype ); AbstractRenderer.prototype.constructor = AbstractRenderer; var prototypeAccessors = { width: { configurable: true },height: { configurable: true },backgroundColor: { configurable: true } }; /** * Initialize the plugins. * * @protected * @param {object} staticMap - The dictionary of statically saved plugins. */ AbstractRenderer.prototype.initPlugins = function initPlugins (staticMap) { for (var o in staticMap) { this.plugins[o] = new (staticMap[o])(this); } }; /** * Same as view.width, actual number of pixels in the canvas by horizontal. * * @member {number} * @readonly * @default 800 */ prototypeAccessors.width.get = function () { return this.view.width; }; /** * Same as view.height, actual number of pixels in the canvas by vertical. * * @member {number} * @readonly * @default 600 */ prototypeAccessors.height.get = function () { return this.view.height; }; /** * Resizes the screen and canvas to the specified width and height. * Canvas dimensions are multiplied by resolution. * * @param {number} screenWidth - The new width of the screen. * @param {number} screenHeight - The new height of the screen. */ AbstractRenderer.prototype.resize = function resize (screenWidth, screenHeight) { this.screen.width = screenWidth; this.screen.height = screenHeight; this.view.width = screenWidth * this.resolution; this.view.height = screenHeight * this.resolution; if (this.autoDensity) { this.view.style.width = screenWidth + "px"; this.view.style.height = screenHeight + "px"; } }; /** * Useful function that returns a texture of the display object that can then be used to create sprites * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. * * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from. * @param {number} scaleMode - Should be one of the scaleMode consts. * @param {number} resolution - The resolution / device pixel ratio of the texture being generated. * @param {PIXI.Rectangle} [region] - The region of the displayObject, that shall be rendered, * if no region is specified, defaults to the local bounds of the displayObject. * @return {PIXI.RenderTexture} A texture of the graphics object. */ AbstractRenderer.prototype.generateTexture = function generateTexture (displayObject, scaleMode, resolution, region) { region = region || displayObject.getLocalBounds(); // minimum texture size is 1x1, 0x0 will throw an error if (region.width === 0) { region.width = 1; } if (region.height === 0) { region.height = 1; } var renderTexture = RenderTexture.create(region.width | 0, region.height | 0, scaleMode, resolution); tempMatrix.tx = -region.x; tempMatrix.ty = -region.y; this.render(displayObject, renderTexture, false, tempMatrix, !!displayObject.parent); return renderTexture; }; /** * Removes everything from the renderer and optionally removes the Canvas DOM element. * * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. */ AbstractRenderer.prototype.destroy = function destroy (removeView) { for (var o in this.plugins) { this.plugins[o].destroy(); this.plugins[o] = null; } if (removeView && this.view.parentNode) { this.view.parentNode.removeChild(this.view); } this.plugins = null; this.type = constants.RENDERER_TYPE.UNKNOWN; this.view = null; this.screen = null; this.resolution = 0; this.transparent = false; this.autoDensity = false; this.blendModes = null; this.options = null; this.preserveDrawingBuffer = false; this.clearBeforeRender = false; this._backgroundColor = 0; this._backgroundColorRgba = null; this._backgroundColorString = null; this._tempDisplayObjectParent = null; this._lastObjectRendered = null; }; /** * The background color to fill if not transparent * * @member {number} */ prototypeAccessors.backgroundColor.get = function () { return this._backgroundColor; }; prototypeAccessors.backgroundColor.set = function (value) // eslint-disable-line require-jsdoc { this._backgroundColor = value; this._backgroundColorString = utils.hex2string(value); utils.hex2rgb(value, this._backgroundColorRgba); }; Object.defineProperties( AbstractRenderer.prototype, prototypeAccessors ); return AbstractRenderer; }(utils.EventEmitter)); /** * The Renderer draws the scene and all its content onto a WebGL enabled canvas. * * This renderer should be used for browsers that support WebGL. * * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds. * Don't forget to add the view to your DOM or you will not see anything! * * @class * @memberof PIXI * @extends PIXI.AbstractRenderer */ var Renderer = /*@__PURE__*/(function (AbstractRenderer) { function Renderer(options) { if ( options === void 0 ) options = {}; AbstractRenderer.call(this, 'WebGL', options); // the options will have been modified here in the super constructor with pixi's default settings.. options = this.options; /** * The type of this renderer as a standardized const * * @member {number} * @see PIXI.RENDERER_TYPE */ this.type = constants.RENDERER_TYPE.WEBGL; /** * WebGL context, set by the contextSystem (this.context) * * @readonly * @member {WebGLRenderingContext} */ this.gl = null; this.CONTEXT_UID = 0; // TODO legacy! /** * Internal signal instances of **runner**, these * are assigned to each system created. * @see PIXI.Runner * @name PIXI.Renderer#runners * @private * @type {object} * @readonly * @property {PIXI.Runner} destroy - Destroy runner * @property {PIXI.Runner} contextChange - Context change runner * @property {PIXI.Runner} reset - Reset runner * @property {PIXI.Runner} update - Update runner * @property {PIXI.Runner} postrender - Post-render runner * @property {PIXI.Runner} prerender - Pre-render runner * @property {PIXI.Runner} resize - Resize runner */ this.runners = { destroy: new runner.Runner('destroy'), contextChange: new runner.Runner('contextChange', 1), reset: new runner.Runner('reset'), update: new runner.Runner('update'), postrender: new runner.Runner('postrender'), prerender: new runner.Runner('prerender'), resize: new runner.Runner('resize', 2), }; /** * Global uniforms * @member {PIXI.UniformGroup} */ this.globalUniforms = new UniformGroup({ projectionMatrix: new math.Matrix(), }, true); /** * Mask system instance * @member {PIXI.systems.MaskSystem} mask * @memberof PIXI.Renderer# * @readonly */ this.addSystem(MaskSystem, 'mask') /** * Context system instance * @member {PIXI.systems.ContextSystem} context * @memberof PIXI.Renderer# * @readonly */ .addSystem(ContextSystem, 'context') /** * State system instance * @member {PIXI.systems.StateSystem} state * @memberof PIXI.Renderer# * @readonly */ .addSystem(StateSystem, 'state') /** * Shader system instance * @member {PIXI.systems.ShaderSystem} shader * @memberof PIXI.Renderer# * @readonly */ .addSystem(ShaderSystem, 'shader') /** * Texture system instance * @member {PIXI.systems.TextureSystem} texture * @memberof PIXI.Renderer# * @readonly */ .addSystem(TextureSystem, 'texture') /** * Geometry system instance * @member {PIXI.systems.GeometrySystem} geometry * @memberof PIXI.Renderer# * @readonly */ .addSystem(GeometrySystem, 'geometry') /** * Framebuffer system instance * @member {PIXI.systems.FramebufferSystem} framebuffer * @memberof PIXI.Renderer# * @readonly */ .addSystem(FramebufferSystem, 'framebuffer') /** * Scissor system instance * @member {PIXI.systems.ScissorSystem} scissor * @memberof PIXI.Renderer# * @readonly */ .addSystem(ScissorSystem, 'scissor') /** * Stencil system instance * @member {PIXI.systems.StencilSystem} stencil * @memberof PIXI.Renderer# * @readonly */ .addSystem(StencilSystem, 'stencil') /** * Projection system instance * @member {PIXI.systems.ProjectionSystem} projection * @memberof PIXI.Renderer# * @readonly */ .addSystem(ProjectionSystem, 'projection') /** * Texture garbage collector system instance * @member {PIXI.systems.TextureGCSystem} textureGC * @memberof PIXI.Renderer# * @readonly */ .addSystem(TextureGCSystem, 'textureGC') /** * Filter system instance * @member {PIXI.systems.FilterSystem} filter * @memberof PIXI.Renderer# * @readonly */ .addSystem(FilterSystem, 'filter') /** * RenderTexture system instance * @member {PIXI.systems.RenderTextureSystem} renderTexture * @memberof PIXI.Renderer# * @readonly */ .addSystem(RenderTextureSystem, 'renderTexture') /** * Batch system instance * @member {PIXI.systems.BatchSystem} batch * @memberof PIXI.Renderer# * @readonly */ .addSystem(BatchSystem, 'batch'); this.initPlugins(Renderer.__plugins); /** * The options passed in to create a new WebGL context. */ if (options.context) { this.context.initFromContext(options.context); } else { this.context.initFromOptions({ alpha: this.transparent, antialias: options.antialias, premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', stencil: true, preserveDrawingBuffer: options.preserveDrawingBuffer, powerPreference: this.options.powerPreference, }); } /** * Flag if we are rendering to the screen vs renderTexture * @member {boolean} * @readonly * @default true */ this.renderingToScreen = true; utils.sayHello(this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1'); this.resize(this.options.width, this.options.height); } if ( AbstractRenderer ) Renderer.__proto__ = AbstractRenderer; Renderer.prototype = Object.create( AbstractRenderer && AbstractRenderer.prototype ); Renderer.prototype.constructor = Renderer; /** * Add a new system to the renderer. * @param {Function} ClassRef - Class reference * @param {string} [name] - Property name for system, if not specified * will use a static `name` property on the class itself. This * name will be assigned as s property on the Renderer so make * sure it doesn't collide with properties on Renderer. * @return {PIXI.Renderer} Return instance of renderer */ Renderer.create = function create (options) { if (utils.isWebGLSupported()) { return new Renderer(options); } throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.'); }; Renderer.prototype.addSystem = function addSystem (ClassRef, name) { if (!name) { name = ClassRef.name; } var system = new ClassRef(this); if (this[name]) { throw new Error(("Whoops! The name \"" + name + "\" is already in use")); } this[name] = system; for (var i in this.runners) { this.runners[i].add(system); } /** * Fired after rendering finishes. * * @event PIXI.Renderer#postrender */ /** * Fired before rendering starts. * * @event PIXI.Renderer#prerender */ /** * Fired when the WebGL context is set. * * @event PIXI.Renderer#context * @param {WebGLRenderingContext} gl - WebGL context. */ return this; }; /** * Renders the object to its WebGL view * * @param {PIXI.DisplayObject} displayObject - The object to be rendered. * @param {PIXI.RenderTexture} [renderTexture] - The render texture to render to. * @param {boolean} [clear=true] - Should the canvas be cleared before the new render. * @param {PIXI.Matrix} [transform] - A transform to apply to the render texture before rendering. * @param {boolean} [skipUpdateTransform=false] - Should we skip the update transform pass? */ Renderer.prototype.render = function render (displayObject, renderTexture, clear, transform, skipUpdateTransform) { // can be handy to know! this.renderingToScreen = !renderTexture; this.runners.prerender.run(); this.emit('prerender'); // apply a transform at a GPU level this.projection.transform = transform; // no point rendering if our context has been blown up! if (this.context.isLost) { return; } if (!renderTexture) { this._lastObjectRendered = displayObject; } if (!skipUpdateTransform) { // update the scene graph var cacheParent = displayObject.parent; displayObject.parent = this._tempDisplayObjectParent; displayObject.updateTransform(); displayObject.parent = cacheParent; // displayObject.hitArea = //TODO add a temp hit area } this.renderTexture.bind(renderTexture); this.batch.currentRenderer.start(); if (clear !== undefined ? clear : this.clearBeforeRender) { this.renderTexture.clear(); } displayObject.render(this); // apply transform.. this.batch.currentRenderer.flush(); if (renderTexture) { renderTexture.baseTexture.update(); } this.runners.postrender.run(); // reset transform after render this.projection.transform = null; this.emit('postrender'); }; /** * Resizes the WebGL view to the specified width and height. * * @param {number} screenWidth - The new width of the screen. * @param {number} screenHeight - The new height of the screen. */ Renderer.prototype.resize = function resize (screenWidth, screenHeight) { AbstractRenderer.prototype.resize.call(this, screenWidth, screenHeight); this.runners.resize.run(screenWidth, screenHeight); }; /** * Resets the WebGL state so you can render things however you fancy! * * @return {PIXI.Renderer} Returns itself. */ Renderer.prototype.reset = function reset () { this.runners.reset.run(); return this; }; /** * Clear the frame buffer */ Renderer.prototype.clear = function clear () { this.framebuffer.bind(); this.framebuffer.clear(); }; /** * Removes everything from the renderer (event listeners, spritebatch, etc...) * * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. * See: https://github.com/pixijs/pixi.js/issues/2233 */ Renderer.prototype.destroy = function destroy (removeView) { this.runners.destroy.run(); for (var r in this.runners) { this.runners[r].destroy(); } // call base destroy AbstractRenderer.prototype.destroy.call(this, removeView); // TODO nullify all the managers.. this.gl = null; }; /** * Collection of installed plugins. These are included by default in PIXI, but can be excluded * by creating a custom build. Consult the README for more information about creating custom * builds and excluding plugins. * @name PIXI.Renderer#plugins * @type {object} * @readonly * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. * @property {PIXI.Extract} extract Extract image data from renderer. * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. * @property {PIXI.Prepare} prepare Pre-render display objects. */ /** * Adds a plugin to the renderer. * * @method * @param {string} pluginName - The name of the plugin. * @param {Function} ctor - The constructor function or class for the plugin. */ Renderer.registerPlugin = function registerPlugin (pluginName, ctor) { Renderer.__plugins = Renderer.__plugins || {}; Renderer.__plugins[pluginName] = ctor; }; return Renderer; }(AbstractRenderer)); /** * This helper function will automatically detect which renderer you should be using. * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by * the browser then this function will return a canvas renderer * * @memberof PIXI * @function autoDetectRenderer * @param {object} [options] - The optional renderer parameters * @param {number} [options.width=800] - the width of the renderers view * @param {number} [options.height=600] - the height of the renderers view * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional * @param {boolean} [options.transparent=false] - If the render view is transparent, default false * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for * resolutions other than 1 * @param {boolean} [options.antialias=false] - sets antialias * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you * need to call toDataUrl on the webgl context * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area * (shown if not transparent). * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or * not before the new render pass. * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise * it is ignored. * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. * FXAA is faster, but may not always look as great **webgl only** * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" * for devices with dual graphics card **webgl only** * @return {PIXI.Renderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ function autoDetectRenderer(options) { return Renderer.create(options); } var _default = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; var defaultFilter = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; /** * A Texture that depends on six other resources. * * @class * @extends PIXI.BaseTexture * @memberof PIXI */ var CubeTexture = /*@__PURE__*/(function (BaseTexture) { function CubeTexture () { BaseTexture.apply(this, arguments); } if ( BaseTexture ) CubeTexture.__proto__ = BaseTexture; CubeTexture.prototype = Object.create( BaseTexture && BaseTexture.prototype ); CubeTexture.prototype.constructor = CubeTexture; CubeTexture.from = function from (resources, options) { return new CubeTexture(new CubeResource(resources, options)); }; return CubeTexture; }(BaseTexture)); /** * Used by the batcher to draw batches. * Each one of these contains all information required to draw a bound geometry. * * @class * @memberof PIXI */ var BatchDrawCall = function BatchDrawCall() { this.texArray = null; this.blend = 0; this.type = constants.DRAW_MODES.TRIANGLES; this.start = 0; this.size = 0; /** * data for uniforms or custom webgl state * @member {object} */ this.data = null; }; /** * Used by the batcher to build texture batches. * Holds list of textures and their respective locations. * * @class * @memberof PIXI */ var BatchTextureArray = function BatchTextureArray() { /** * inside textures array * @member {PIXI.BaseTexture[]} */ this.elements = []; /** * Respective locations for textures * @member {number[]} */ this.ids = []; /** * number of filled elements * @member {number} */ this.count = 0; }; BatchTextureArray.prototype.clear = function clear () { for (var i = 0; i < this.count; i++) { this.elements[i] = null; } this.count = 0; }; /** * Flexible wrapper around `ArrayBuffer` that also provides * typed array views on demand. * * @class * @memberof PIXI */ var ViewableBuffer = function ViewableBuffer(size) { /** * Underlying `ArrayBuffer` that holds all the data * and is of capacity `size`. * * @member {ArrayBuffer} */ this.rawBinaryData = new ArrayBuffer(size); /** * View on the raw binary data as a `Uint32Array`. * * @member {Uint32Array} */ this.uint32View = new Uint32Array(this.rawBinaryData); /** * View on the raw binary data as a `Float32Array`. * * @member {Float32Array} */ this.float32View = new Float32Array(this.rawBinaryData); }; var prototypeAccessors$5 = { int8View: { configurable: true },uint8View: { configurable: true },int16View: { configurable: true },uint16View: { configurable: true },int32View: { configurable: true } }; /** * View on the raw binary data as a `Int8Array`. * * @member {Int8Array} */ prototypeAccessors$5.int8View.get = function () { if (!this._int8View) { this._int8View = new Int8Array(this.rawBinaryData); } return this._int8View; }; /** * View on the raw binary data as a `Uint8Array`. * * @member {Uint8Array} */ prototypeAccessors$5.uint8View.get = function () { if (!this._uint8View) { this._uint8View = new Uint8Array(this.rawBinaryData); } return this._uint8View; }; /** * View on the raw binary data as a `Int16Array`. * * @member {Int16Array} */ prototypeAccessors$5.int16View.get = function () { if (!this._int16View) { this._int16View = new Int16Array(this.rawBinaryData); } return this._int16View; }; /** * View on the raw binary data as a `Uint16Array`. * * @member {Uint16Array} */ prototypeAccessors$5.uint16View.get = function () { if (!this._uint16View) { this._uint16View = new Uint16Array(this.rawBinaryData); } return this._uint16View; }; /** * View on the raw binary data as a `Int32Array`. * * @member {Int32Array} */ prototypeAccessors$5.int32View.get = function () { if (!this._int32View) { this._int32View = new Int32Array(this.rawBinaryData); } return this._int32View; }; /** * Returns the view of the given type. * * @param {string} type - One of `int8`, `uint8`, `int16`, *`uint16`, `int32`, `uint32`, and `float32`. * @return {object} typed array of given type */ ViewableBuffer.prototype.view = function view (type) { return this[(type + "View")]; }; /** * Destroys all buffer references. Do not use after calling * this. */ ViewableBuffer.prototype.destroy = function destroy () { this.rawBinaryData = null; this._int8View = null; this._uint8View = null; this._int16View = null; this._uint16View = null; this._int32View = null; this.uint32View = null; this.float32View = null; }; ViewableBuffer.sizeOf = function sizeOf (type) { switch (type) { case 'int8': case 'uint8': return 1; case 'int16': case 'uint16': return 2; case 'int32': case 'uint32': case 'float32': return 4; default: throw new Error((type + " isn't a valid view type")); } }; Object.defineProperties( ViewableBuffer.prototype, prototypeAccessors$5 ); /** * Renderer dedicated to drawing and batching sprites. * * This is the default batch renderer. It buffers objects * with texture-based geometries and renders them in * batches. It uploads multiple textures to the GPU to * reduce to the number of draw calls. * * @class * @protected * @memberof PIXI * @extends PIXI.ObjectRenderer */ var AbstractBatchRenderer = /*@__PURE__*/(function (ObjectRenderer) { function AbstractBatchRenderer(renderer) { ObjectRenderer.call(this, renderer); /** * This is used to generate a shader that can * color each vertex based on a `aTextureId` * attribute that points to an texture in `uSampler`. * * This enables the objects with different textures * to be drawn in the same draw call. * * You can customize your shader by creating your * custom shader generator. * * @member {PIXI.BatchShaderGenerator} * @protected */ this.shaderGenerator = null; /** * The class that represents the geometry of objects * that are going to be batched with this. * * @member {object} * @default PIXI.BatchGeometry * @protected */ this.geometryClass = null; /** * Size of data being buffered per vertex in the * attribute buffers (in floats). By default, the * batch-renderer plugin uses 6: * * | aVertexPosition | 2 | * |-----------------|---| * | aTextureCoords | 2 | * | aColor | 1 | * | aTextureId | 1 | * * @member {number} * @readonly */ this.vertexSize = null; /** * The WebGL state in which this renderer will work. * * @member {PIXI.State} * @readonly */ this.state = State.for2d(); /** * The number of bufferable objects before a flush * occurs automatically. * * @member {number} * @default settings.SPRITE_BATCH_SIZE * 4 */ this.size = settings.settings.SPRITE_BATCH_SIZE * 4; /** * Total count of all vertices used by the currently * buffered objects. * * @member {number} * @private */ this._vertexCount = 0; /** * Total count of all indices used by the currently * buffered objects. * * @member {number} * @private */ this._indexCount = 0; /** * Buffer of objects that are yet to be rendered. * * @member {PIXI.DisplayObject[]} * @private */ this._bufferedElements = []; /** * Data for texture batch builder, helps to save a bit of CPU on a pass * @type {PIXI.BaseTexture[]} * @private */ this._bufferedTextures = []; /** * Number of elements that are buffered and are * waiting to be flushed. * * @member {number} * @private */ this._bufferSize = 0; /** * This shader is generated by `this.shaderGenerator`. * * It is generated specifically to handle the required * number of textures being batched together. * * @member {PIXI.Shader} * @protected */ this._shader = null; /** * Pool of `this.geometryClass` geometry objects * that store buffers. They are used to pass data * to the shader on each draw call. * * These are never re-allocated again, unless a * context change occurs; however, the pool may * be expanded if required. * * @member {PIXI.Geometry[]} * @private * @see PIXI.AbstractBatchRenderer.contextChange */ this._packedGeometries = []; /** * Size of `this._packedGeometries`. It can be expanded * if more than `this._packedGeometryPoolSize` flushes * occur in a single frame. * * @member {number} * @private */ this._packedGeometryPoolSize = 2; /** * A flush may occur multiple times in a single * frame. On iOS devices or when * `settings.CAN_UPLOAD_SAME_BUFFER` is false, the * batch renderer does not upload data to the same * `WebGLBuffer` for performance reasons. * * This is the index into `packedGeometries` that points to * geometry holding the most recent buffers. * * @member {number} * @private */ this._flushId = 0; /** * Pool of `ViewableBuffer` objects that are sorted in * order of increasing size. The flush method uses * the buffer with the least size above the amount * it requires. These are used for passing attributes. * * The first buffer has a size of 8; each subsequent * buffer has double capacity of its previous. * * @member {PIXI.ViewableBuffer[]} * @private * @see PIXI.AbstractBatchRenderer#getAttributeBuffer */ this._aBuffers = {}; /** * Pool of `Uint16Array` objects that are sorted in * order of increasing size. The flush method uses * the buffer with the least size above the amount * it requires. These are used for passing indices. * * The first buffer has a size of 12; each subsequent * buffer has double capacity of its previous. * * @member {Uint16Array[]} * @private * @see PIXI.AbstractBatchRenderer#getIndexBuffer */ this._iBuffers = {}; /** * Maximum number of textures that can be uploaded to * the GPU under the current context. It is initialized * properly in `this.contextChange`. * * @member {number} * @see PIXI.AbstractBatchRenderer#contextChange * @readonly */ this.MAX_TEXTURES = 1; this.renderer.on('prerender', this.onPrerender, this); renderer.runners.contextChange.add(this); this._dcIndex = 0; this._aIndex = 0; this._iIndex = 0; this._attributeBuffer = null; this._indexBuffer = null; this._tempBoundTextures = []; } if ( ObjectRenderer ) AbstractBatchRenderer.__proto__ = ObjectRenderer; AbstractBatchRenderer.prototype = Object.create( ObjectRenderer && ObjectRenderer.prototype ); AbstractBatchRenderer.prototype.constructor = AbstractBatchRenderer; /** * Handles the `contextChange` signal. * * It calculates `this.MAX_TEXTURES` and allocating the * packed-geometry object pool. */ AbstractBatchRenderer.prototype.contextChange = function contextChange () { var gl = this.renderer.gl; if (settings.settings.PREFER_ENV === constants.ENV.WEBGL_LEGACY) { this.MAX_TEXTURES = 1; } else { // step 1: first check max textures the GPU can handle. this.MAX_TEXTURES = Math.min( gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), settings.settings.SPRITE_MAX_TEXTURES); // step 2: check the maximum number of if statements the shader can have too.. this.MAX_TEXTURES = checkMaxIfStatementsInShader( this.MAX_TEXTURES, gl); } this._shader = this.shaderGenerator.generateShader(this.MAX_TEXTURES); // we use the second shader as the first one depending on your browser // may omit aTextureId as it is not used by the shader so is optimized out. for (var i = 0; i < this._packedGeometryPoolSize; i++) { /* eslint-disable max-len */ this._packedGeometries[i] = new (this.geometryClass)(); } this.initFlushBuffers(); }; /** * Makes sure that static and dynamic flush pooled objects have correct dimensions */ AbstractBatchRenderer.prototype.initFlushBuffers = function initFlushBuffers () { var _drawCallPool = AbstractBatchRenderer._drawCallPool; var _textureArrayPool = AbstractBatchRenderer._textureArrayPool; // max draw calls var MAX_SPRITES = this.size / 4; // max texture arrays var MAX_TA = Math.floor(MAX_SPRITES / this.MAX_TEXTURES) + 1; while (_drawCallPool.length < MAX_SPRITES) { _drawCallPool.push(new BatchDrawCall()); } while (_textureArrayPool.length < MAX_TA) { _textureArrayPool.push(new BatchTextureArray()); } for (var i = 0; i < this.MAX_TEXTURES; i++) { this._tempBoundTextures[i] = null; } }; /** * Handles the `prerender` signal. * * It ensures that flushes start from the first geometry * object again. */ AbstractBatchRenderer.prototype.onPrerender = function onPrerender () { this._flushId = 0; }; /** * Buffers the "batchable" object. It need not be rendered * immediately. * * @param {PIXI.DisplayObject} element - the element to render when * using this renderer */ AbstractBatchRenderer.prototype.render = function render (element) { if (!element._texture.valid) { return; } if (this._vertexCount + (element.vertexData.length / 2) > this.size) { this.flush(); } this._vertexCount += element.vertexData.length / 2; this._indexCount += element.indices.length; this._bufferedTextures[this._bufferSize] = element._texture.baseTexture; this._bufferedElements[this._bufferSize++] = element; }; AbstractBatchRenderer.prototype.buildTexturesAndDrawCalls = function buildTexturesAndDrawCalls () { var ref = this; var textures = ref._bufferedTextures; var MAX_TEXTURES = ref.MAX_TEXTURES; var textureArrays = AbstractBatchRenderer._textureArrayPool; var batch = this.renderer.batch; var boundTextures = this._tempBoundTextures; var touch = this.renderer.textureGC.count; var TICK = ++BaseTexture._globalBatch; var countTexArrays = 0; var texArray = textureArrays[0]; var start = 0; batch.copyBoundTextures(boundTextures, MAX_TEXTURES); for (var i = 0; i < this._bufferSize; ++i) { var tex = textures[i]; textures[i] = null; if (tex._batchEnabled === TICK) { continue; } if (texArray.count >= MAX_TEXTURES) { batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); this.buildDrawCalls(texArray, start, i); start = i; texArray = textureArrays[++countTexArrays]; ++TICK; } tex._batchEnabled = TICK; tex.touched = touch; texArray.elements[texArray.count++] = tex; } if (texArray.count > 0) { batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); this.buildDrawCalls(texArray, start, this._bufferSize); ++countTexArrays; ++TICK; } // Clean-up for (var i$1 = 0; i$1 < boundTextures.length; i$1++) { boundTextures[i$1] = null; } BaseTexture._globalBatch = TICK; }; /** * Populating drawcalls for rendering * * @param {PIXI.BatchTextureArray} texArray * @param {number} start * @param {number} finish */ AbstractBatchRenderer.prototype.buildDrawCalls = function buildDrawCalls (texArray, start, finish) { var ref = this; var elements = ref._bufferedElements; var _attributeBuffer = ref._attributeBuffer; var _indexBuffer = ref._indexBuffer; var vertexSize = ref.vertexSize; var drawCalls = AbstractBatchRenderer._drawCallPool; var dcIndex = this._dcIndex; var aIndex = this._aIndex; var iIndex = this._iIndex; var drawCall = drawCalls[dcIndex]; drawCall.start = this._iIndex; drawCall.texArray = texArray; for (var i = start; i < finish; ++i) { var sprite = elements[i]; var tex = sprite._texture.baseTexture; var spriteBlendMode = utils.premultiplyBlendMode[ tex.alphaMode ? 1 : 0][sprite.blendMode]; elements[i] = null; if (start < i && drawCall.blend !== spriteBlendMode) { drawCall.size = iIndex - drawCall.start; start = i; drawCall = drawCalls[++dcIndex]; drawCall.texArray = texArray; drawCall.start = iIndex; } this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); aIndex += sprite.vertexData.length / 2 * vertexSize; iIndex += sprite.indices.length; drawCall.blend = spriteBlendMode; } if (start < finish) { drawCall.size = iIndex - drawCall.start; ++dcIndex; } this._dcIndex = dcIndex; this._aIndex = aIndex; this._iIndex = iIndex; }; /** * Bind textures for current rendering * * @param {PIXI.BatchTextureArray} texArray */ AbstractBatchRenderer.prototype.bindAndClearTexArray = function bindAndClearTexArray (texArray) { var textureSystem = this.renderer.texture; for (var j = 0; j < texArray.count; j++) { textureSystem.bind(texArray.elements[j], texArray.ids[j]); texArray.elements[j] = null; } texArray.count = 0; }; AbstractBatchRenderer.prototype.updateGeometry = function updateGeometry () { var ref = this; var packedGeometries = ref._packedGeometries; var attributeBuffer = ref._attributeBuffer; var indexBuffer = ref._indexBuffer; if (!settings.settings.CAN_UPLOAD_SAME_BUFFER) { /* Usually on iOS devices, where the browser doesn't like uploads to the same buffer in a single frame. */ if (this._packedGeometryPoolSize <= this._flushId) { this._packedGeometryPoolSize++; packedGeometries[this._flushId] = new (this.geometryClass)(); } packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); this.renderer.geometry.bind(packedGeometries[this._flushId]); this.renderer.geometry.updateBuffers(); this._flushId++; } else { // lets use the faster option, always use buffer number 0 packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); this.renderer.geometry.updateBuffers(); } }; AbstractBatchRenderer.prototype.drawBatches = function drawBatches () { var dcCount = this._dcIndex; var ref = this.renderer; var gl = ref.gl; var stateSystem = ref.state; var drawCalls = AbstractBatchRenderer._drawCallPool; var curTexArray = null; // Upload textures and do the draw calls for (var i = 0; i < dcCount; i++) { var ref$1 = drawCalls[i]; var texArray = ref$1.texArray; var type = ref$1.type; var size = ref$1.size; var start = ref$1.start; var blend = ref$1.blend; if (curTexArray !== texArray) { curTexArray = texArray; this.bindAndClearTexArray(texArray); } this.state.blendMode = blend; stateSystem.set(this.state); gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); } }; /** * Renders the content _now_ and empties the current batch. */ AbstractBatchRenderer.prototype.flush = function flush () { if (this._vertexCount === 0) { return; } this._attributeBuffer = this.getAttributeBuffer(this._vertexCount); this._indexBuffer = this.getIndexBuffer(this._indexCount); this._aIndex = 0; this._iIndex = 0; this._dcIndex = 0; this.buildTexturesAndDrawCalls(); this.updateGeometry(); this.drawBatches(); // reset elements buffer for the next flush this._bufferSize = 0; this._vertexCount = 0; this._indexCount = 0; }; /** * Starts a new sprite batch. */ AbstractBatchRenderer.prototype.start = function start () { this.renderer.state.set(this.state); this.renderer.shader.bind(this._shader); if (settings.settings.CAN_UPLOAD_SAME_BUFFER) { // bind buffer #0, we don't need others this.renderer.geometry.bind(this._packedGeometries[this._flushId]); } }; /** * Stops and flushes the current batch. */ AbstractBatchRenderer.prototype.stop = function stop () { this.flush(); }; /** * Destroys this `AbstractBatchRenderer`. It cannot be used again. */ AbstractBatchRenderer.prototype.destroy = function destroy () { for (var i = 0; i < this._packedGeometryPoolSize; i++) { if (this._packedGeometries[i]) { this._packedGeometries[i].destroy(); } } this.renderer.off('prerender', this.onPrerender, this); this._aBuffers = null; this._iBuffers = null; this._packedGeometries = null; this._attributeBuffer = null; this._indexBuffer = null; if (this._shader) { this._shader.destroy(); this._shader = null; } ObjectRenderer.prototype.destroy.call(this); }; /** * Fetches an attribute buffer from `this._aBuffers` that * can hold atleast `size` floats. * * @param {number} size - minimum capacity required * @return {ViewableBuffer} - buffer than can hold atleast `size` floats * @private */ AbstractBatchRenderer.prototype.getAttributeBuffer = function getAttributeBuffer (size) { // 8 vertices is enough for 2 quads var roundedP2 = utils.nextPow2(Math.ceil(size / 8)); var roundedSizeIndex = utils.log2(roundedP2); var roundedSize = roundedP2 * 8; if (this._aBuffers.length <= roundedSizeIndex) { this._iBuffers.length = roundedSizeIndex + 1; } var buffer = this._aBuffers[roundedSize]; if (!buffer) { this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4); } return buffer; }; /** * Fetches an index buffer from `this._iBuffers` that can * has atleast `size` capacity. * * @param {number} size - minimum required capacity * @return {Uint16Array} - buffer that can fit `size` * indices. * @private */ AbstractBatchRenderer.prototype.getIndexBuffer = function getIndexBuffer (size) { // 12 indices is enough for 2 quads var roundedP2 = utils.nextPow2(Math.ceil(size / 12)); var roundedSizeIndex = utils.log2(roundedP2); var roundedSize = roundedP2 * 12; if (this._iBuffers.length <= roundedSizeIndex) { this._iBuffers.length = roundedSizeIndex + 1; } var buffer = this._iBuffers[roundedSizeIndex]; if (!buffer) { this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize); } return buffer; }; /** * Takes the four batching parameters of `element`, interleaves * and pushes them into the batching attribute/index buffers given. * * It uses these properties: `vertexData` `uvs`, `textureId` and * `indicies`. It also uses the "tint" of the base-texture, if * present. * * @param {PIXI.Sprite} element - element being rendered * @param {PIXI.ViewableBuffer} attributeBuffer - attribute buffer. * @param {Uint16Array} indexBuffer - index buffer * @param {number} aIndex - number of floats already in the attribute buffer * @param {number} iIndex - number of indices already in `indexBuffer` */ AbstractBatchRenderer.prototype.packInterleavedGeometry = function packInterleavedGeometry (element, attributeBuffer, indexBuffer, aIndex, iIndex) { var uint32View = attributeBuffer.uint32View; var float32View = attributeBuffer.float32View; var packedVertices = aIndex / this.vertexSize; var uvs = element.uvs; var indicies = element.indices; var vertexData = element.vertexData; var textureId = element._texture.baseTexture._batchLocation; var alpha = Math.min(element.worldAlpha, 1.0); var argb = (alpha < 1.0 && element._texture.baseTexture.alphaMode) ? utils.premultiplyTint(element._tintRGB, alpha) : element._tintRGB + (alpha * 255 << 24); // lets not worry about tint! for now.. for (var i = 0; i < vertexData.length; i += 2) { float32View[aIndex++] = vertexData[i]; float32View[aIndex++] = vertexData[i + 1]; float32View[aIndex++] = uvs[i]; float32View[aIndex++] = uvs[i + 1]; uint32View[aIndex++] = argb; float32View[aIndex++] = textureId; } for (var i$1 = 0; i$1 < indicies.length; i$1++) { indexBuffer[iIndex++] = packedVertices + indicies[i$1]; } }; return AbstractBatchRenderer; }(ObjectRenderer)); /** * Pool of `BatchDrawCall` objects that `flush` used * to create "batches" of the objects being rendered. * * These are never re-allocated again. * Shared between all batch renderers because it can be only one "flush" working at the moment. * * @static * @member {PIXI.BatchDrawCall[]} */ AbstractBatchRenderer._drawCallPool = []; /** * Pool of `BatchDrawCall` objects that `flush` used * to create "batches" of the objects being rendered. * * These are never re-allocated again. * Shared between all batch renderers because it can be only one "flush" working at the moment. * * @static * @member {PIXI.BatchTextureArray[]} */ AbstractBatchRenderer._textureArrayPool = []; /** * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer * * @class * @memberof PIXI */ var BatchShaderGenerator = function BatchShaderGenerator(vertexSrc, fragTemplate) { /** * Reference to the vertex shader source. * * @member {string} */ this.vertexSrc = vertexSrc; /** * Reference to the fragement shader template. Must contain "%count%" and "%forloop%". * * @member {string} */ this.fragTemplate = fragTemplate; this.programCache = {}; this.defaultGroupCache = {}; if (fragTemplate.indexOf('%count%') < 0) { throw new Error('Fragment template must contain "%count%".'); } if (fragTemplate.indexOf('%forloop%') < 0) { throw new Error('Fragment template must contain "%forloop%".'); } }; BatchShaderGenerator.prototype.generateShader = function generateShader (maxTextures) { if (!this.programCache[maxTextures]) { var sampleValues = new Int32Array(maxTextures); for (var i = 0; i < maxTextures; i++) { sampleValues[i] = i; } this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true); var fragmentSrc = this.fragTemplate; fragmentSrc = fragmentSrc.replace(/%count%/gi, ("" + maxTextures)); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)); this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc); } var uniforms = { tint: new Float32Array([1, 1, 1, 1]), translationMatrix: new math.Matrix(), default: this.defaultGroupCache[maxTextures], }; return new Shader(this.programCache[maxTextures], uniforms); }; BatchShaderGenerator.prototype.generateSampleSrc = function generateSampleSrc (maxTextures) { var src = ''; src += '\n'; src += '\n'; for (var i = 0; i < maxTextures; i++) { if (i > 0) { src += '\nelse '; } if (i < maxTextures - 1) { src += "if(vTextureId < " + i + ".5)"; } src += '\n{'; src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);"; src += '\n}'; } src += '\n'; src += '\n'; return src; }; /** * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects). * * @class * @memberof PIXI */ var BatchGeometry = /*@__PURE__*/(function (Geometry) { function BatchGeometry(_static) { if ( _static === void 0 ) _static = false; Geometry.call(this); /** * Buffer used for position, color, texture IDs * * @member {PIXI.Buffer} * @protected */ this._buffer = new Buffer(null, _static, false); /** * Index buffer data * * @member {PIXI.Buffer} * @protected */ this._indexBuffer = new Buffer(null, _static, true); this.addAttribute('aVertexPosition', this._buffer, 2, false, constants.TYPES.FLOAT) .addAttribute('aTextureCoord', this._buffer, 2, false, constants.TYPES.FLOAT) .addAttribute('aColor', this._buffer, 4, true, constants.TYPES.UNSIGNED_BYTE) .addAttribute('aTextureId', this._buffer, 1, true, constants.TYPES.FLOAT) .addIndex(this._indexBuffer); } if ( Geometry ) BatchGeometry.__proto__ = Geometry; BatchGeometry.prototype = Object.create( Geometry && Geometry.prototype ); BatchGeometry.prototype.constructor = BatchGeometry; return BatchGeometry; }(Geometry)); var defaultVertex$2 = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"; var defaultFragment$2 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"; /** * @class * @memberof PIXI * @hideconstructor */ var BatchPluginFactory = function BatchPluginFactory () {}; var staticAccessors$1 = { defaultVertexSrc: { configurable: true },defaultFragmentTemplate: { configurable: true } }; BatchPluginFactory.create = function create (options) { var ref = Object.assign({ vertex: defaultVertex$2, fragment: defaultFragment$2, geometryClass: BatchGeometry, vertexSize: 6, }, options); var vertex = ref.vertex; var fragment = ref.fragment; var vertexSize = ref.vertexSize; var geometryClass = ref.geometryClass; return /*@__PURE__*/(function (AbstractBatchRenderer) { function BatchPlugin(renderer) { AbstractBatchRenderer.call(this, renderer); this.shaderGenerator = new BatchShaderGenerator(vertex, fragment); this.geometryClass = geometryClass; this.vertexSize = vertexSize; } if ( AbstractBatchRenderer ) BatchPlugin.__proto__ = AbstractBatchRenderer; BatchPlugin.prototype = Object.create( AbstractBatchRenderer && AbstractBatchRenderer.prototype ); BatchPlugin.prototype.constructor = BatchPlugin; return BatchPlugin; }(AbstractBatchRenderer)); }; /** * The default vertex shader source * * @static * @type {string} * @constant */ staticAccessors$1.defaultVertexSrc.get = function () { return defaultVertex$2; }; /** * The default fragment shader source * * @static * @type {string} * @constant */ staticAccessors$1.defaultFragmentTemplate.get = function () { return defaultFragment$2; }; Object.defineProperties( BatchPluginFactory, staticAccessors$1 ); // Setup the default BatchRenderer plugin, this is what // we'll actually export at the root level var BatchRenderer = BatchPluginFactory.create(); exports.AbstractBatchRenderer = AbstractBatchRenderer; exports.AbstractRenderer = AbstractRenderer; exports.Attribute = Attribute; exports.BaseRenderTexture = BaseRenderTexture; exports.BaseTexture = BaseTexture; exports.BatchDrawCall = BatchDrawCall; exports.BatchGeometry = BatchGeometry; exports.BatchPluginFactory = BatchPluginFactory; exports.BatchRenderer = BatchRenderer; exports.BatchShaderGenerator = BatchShaderGenerator; exports.BatchTextureArray = BatchTextureArray; exports.Buffer = Buffer; exports.CubeTexture = CubeTexture; exports.Filter = Filter; exports.Framebuffer = Framebuffer; exports.GLProgram = GLProgram; exports.GLTexture = GLTexture; exports.Geometry = Geometry; exports.MaskData = MaskData; exports.ObjectRenderer = ObjectRenderer; exports.Program = Program; exports.Quad = Quad; exports.QuadUv = QuadUv; exports.RenderTexture = RenderTexture; exports.RenderTexturePool = RenderTexturePool; exports.Renderer = Renderer; exports.Shader = Shader; exports.SpriteMaskFilter = SpriteMaskFilter; exports.State = State; exports.System = System; exports.Texture = Texture; exports.TextureMatrix = TextureMatrix; exports.TextureUvs = TextureUvs; exports.UniformGroup = UniformGroup; exports.ViewableBuffer = ViewableBuffer; exports.autoDetectRenderer = autoDetectRenderer; exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader; exports.defaultFilterVertex = defaultFilter; exports.defaultVertex = _default; exports.resources = index; exports.systems = systems; },{"@pixi/constants":6,"@pixi/display":8,"@pixi/math":21,"@pixi/runner":30,"@pixi/settings":31,"@pixi/ticker":38,"@pixi/utils":39}],8:[function(require,module,exports){ /*! * @pixi/display - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/display is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var settings = require('@pixi/settings'); var math = require('@pixi/math'); var utils = require('@pixi/utils'); /** * Sets the default value for the container property 'sortableChildren'. * If set to true, the container will sort its children by zIndex value * when updateTransform() is called, or manually if sortChildren() is called. * * This actually changes the order of elements in the array, so should be treated * as a basic solution that is not performant compared to other solutions, * such as @link https://github.com/pixijs/pixi-display * * Also be aware of that this may not work nicely with the addChildAt() function, * as the zIndex sorting may cause the child to automatically sorted to another position. * * @static * @constant * @name SORTABLE_CHILDREN * @memberof PIXI.settings * @type {boolean} * @default false */ settings.settings.SORTABLE_CHILDREN = false; /** * 'Builder' pattern for bounds rectangles. * * This could be called an Axis-Aligned Bounding Box. * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems. * * @class * @memberof PIXI */ var Bounds = function Bounds() { /** * @member {number} * @default 0 */ this.minX = Infinity; /** * @member {number} * @default 0 */ this.minY = Infinity; /** * @member {number} * @default 0 */ this.maxX = -Infinity; /** * @member {number} * @default 0 */ this.maxY = -Infinity; this.rect = null; }; /** * Checks if bounds are empty. * * @return {boolean} True if empty. */ Bounds.prototype.isEmpty = function isEmpty () { return this.minX > this.maxX || this.minY > this.maxY; }; /** * Clears the bounds and resets. * */ Bounds.prototype.clear = function clear () { this.minX = Infinity; this.minY = Infinity; this.maxX = -Infinity; this.maxY = -Infinity; }; /** * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle * It is not guaranteed that it will return tempRect * * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty * @returns {PIXI.Rectangle} A rectangle of the bounds */ Bounds.prototype.getRectangle = function getRectangle (rect) { if (this.minX > this.maxX || this.minY > this.maxY) { return math.Rectangle.EMPTY; } rect = rect || new math.Rectangle(0, 0, 1, 1); rect.x = this.minX; rect.y = this.minY; rect.width = this.maxX - this.minX; rect.height = this.maxY - this.minY; return rect; }; /** * This function should be inlined when its possible. * * @param {PIXI.Point} point - The point to add. */ Bounds.prototype.addPoint = function addPoint (point) { this.minX = Math.min(this.minX, point.x); this.maxX = Math.max(this.maxX, point.x); this.minY = Math.min(this.minY, point.y); this.maxY = Math.max(this.maxY, point.y); }; /** * Adds a quad, not transformed * * @param {Float32Array} vertices - The verts to add. */ Bounds.prototype.addQuad = function addQuad (vertices) { var minX = this.minX; var minY = this.minY; var maxX = this.maxX; var maxY = this.maxY; var x = vertices[0]; var y = vertices[1]; minX = x < minX ? x : minX; minY = y < minY ? y : minY; maxX = x > maxX ? x : maxX; maxY = y > maxY ? y : maxY; x = vertices[2]; y = vertices[3]; minX = x < minX ? x : minX; minY = y < minY ? y : minY; maxX = x > maxX ? x : maxX; maxY = y > maxY ? y : maxY; x = vertices[4]; y = vertices[5]; minX = x < minX ? x : minX; minY = y < minY ? y : minY; maxX = x > maxX ? x : maxX; maxY = y > maxY ? y : maxY; x = vertices[6]; y = vertices[7]; minX = x < minX ? x : minX; minY = y < minY ? y : minY; maxX = x > maxX ? x : maxX; maxY = y > maxY ? y : maxY; this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; }; /** * Adds sprite frame, transformed. * * @param {PIXI.Transform} transform - transform to apply * @param {number} x0 - left X of frame * @param {number} y0 - top Y of frame * @param {number} x1 - right X of frame * @param {number} y1 - bottom Y of frame */ Bounds.prototype.addFrame = function addFrame (transform, x0, y0, x1, y1) { this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1); }; /** * Adds sprite frame, multiplied by matrix * * @param {PIXI.Matrix} matrix - matrix to apply * @param {number} x0 - left X of frame * @param {number} y0 - top Y of frame * @param {number} x1 - right X of frame * @param {number} y1 - bottom Y of frame */ Bounds.prototype.addFrameMatrix = function addFrameMatrix (matrix, x0, y0, x1, y1) { var a = matrix.a; var b = matrix.b; var c = matrix.c; var d = matrix.d; var tx = matrix.tx; var ty = matrix.ty; var minX = this.minX; var minY = this.minY; var maxX = this.maxX; var maxY = this.maxY; var x = (a * x0) + (c * y0) + tx; var y = (b * x0) + (d * y0) + ty; minX = x < minX ? x : minX; minY = y < minY ? y : minY; maxX = x > maxX ? x : maxX; maxY = y > maxY ? y : maxY; x = (a * x1) + (c * y0) + tx; y = (b * x1) + (d * y0) + ty; minX = x < minX ? x : minX; minY = y < minY ? y : minY; maxX = x > maxX ? x : maxX; maxY = y > maxY ? y : maxY; x = (a * x0) + (c * y1) + tx; y = (b * x0) + (d * y1) + ty; minX = x < minX ? x : minX; minY = y < minY ? y : minY; maxX = x > maxX ? x : maxX; maxY = y > maxY ? y : maxY; x = (a * x1) + (c * y1) + tx; y = (b * x1) + (d * y1) + ty; minX = x < minX ? x : minX; minY = y < minY ? y : minY; maxX = x > maxX ? x : maxX; maxY = y > maxY ? y : maxY; this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; }; /** * Adds screen vertices from array * * @param {Float32Array} vertexData - calculated vertices * @param {number} beginOffset - begin offset * @param {number} endOffset - end offset, excluded */ Bounds.prototype.addVertexData = function addVertexData (vertexData, beginOffset, endOffset) { var minX = this.minX; var minY = this.minY; var maxX = this.maxX; var maxY = this.maxY; for (var i = beginOffset; i < endOffset; i += 2) { var x = vertexData[i]; var y = vertexData[i + 1]; minX = x < minX ? x : minX; minY = y < minY ? y : minY; maxX = x > maxX ? x : maxX; maxY = y > maxY ? y : maxY; } this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; }; /** * Add an array of mesh vertices * * @param {PIXI.Transform} transform - mesh transform * @param {Float32Array} vertices - mesh coordinates in array * @param {number} beginOffset - begin offset * @param {number} endOffset - end offset, excluded */ Bounds.prototype.addVertices = function addVertices (transform, vertices, beginOffset, endOffset) { this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset); }; /** * Add an array of mesh vertices * * @param {PIXI.Matrix} matrix - mesh matrix * @param {Float32Array} vertices - mesh coordinates in array * @param {number} beginOffset - begin offset * @param {number} endOffset - end offset, excluded * @param {number} [padX] - x padding * @param {number} [padY] - y padding */ Bounds.prototype.addVerticesMatrix = function addVerticesMatrix (matrix, vertices, beginOffset, endOffset, padX, padY) { var a = matrix.a; var b = matrix.b; var c = matrix.c; var d = matrix.d; var tx = matrix.tx; var ty = matrix.ty; padX = padX || 0; padY = padY || 0; var minX = this.minX; var minY = this.minY; var maxX = this.maxX; var maxY = this.maxY; for (var i = beginOffset; i < endOffset; i += 2) { var rawX = vertices[i]; var rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; minX = Math.min(minX, x - padX); maxX = Math.max(maxX, x + padX); minY = Math.min(minY, y - padY); maxY = Math.max(maxY, y + padY); } this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; }; /** * Adds other Bounds * * @param {PIXI.Bounds} bounds - TODO */ Bounds.prototype.addBounds = function addBounds (bounds) { var minX = this.minX; var minY = this.minY; var maxX = this.maxX; var maxY = this.maxY; this.minX = bounds.minX < minX ? bounds.minX : minX; this.minY = bounds.minY < minY ? bounds.minY : minY; this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; }; /** * Adds other Bounds, masked with Bounds * * @param {PIXI.Bounds} bounds - TODO * @param {PIXI.Bounds} mask - TODO */ Bounds.prototype.addBoundsMask = function addBoundsMask (bounds, mask) { var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; if (_minX <= _maxX && _minY <= _maxY) { var minX = this.minX; var minY = this.minY; var maxX = this.maxX; var maxY = this.maxY; this.minX = _minX < minX ? _minX : minX; this.minY = _minY < minY ? _minY : minY; this.maxX = _maxX > maxX ? _maxX : maxX; this.maxY = _maxY > maxY ? _maxY : maxY; } }; /** * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty * * @param {PIXI.Bounds} bounds other bounds * @param {PIXI.Matrix} matrix multiplicator */ Bounds.prototype.addBoundsMatrix = function addBoundsMatrix (bounds, matrix) { this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); }; /** * Adds other Bounds, masked with Rectangle * * @param {PIXI.Bounds} bounds - TODO * @param {PIXI.Rectangle} area - TODO */ Bounds.prototype.addBoundsArea = function addBoundsArea (bounds, area) { var _minX = bounds.minX > area.x ? bounds.minX : area.x; var _minY = bounds.minY > area.y ? bounds.minY : area.y; var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width); var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height); if (_minX <= _maxX && _minY <= _maxY) { var minX = this.minX; var minY = this.minY; var maxX = this.maxX; var maxY = this.maxY; this.minX = _minX < minX ? _minX : minX; this.minY = _minY < minY ? _minY : minY; this.maxX = _maxX > maxX ? _maxX : maxX; this.maxY = _maxY > maxY ? _maxY : maxY; } }; /** * Pads bounds object, making it grow in all directions. * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. * * @param {number} [paddingX=0] - The horizontal padding amount. * @param {number} [paddingY=0] - The vertical padding amount. */ Bounds.prototype.pad = function pad (paddingX, paddingY) { paddingX = paddingX || 0; paddingY = paddingY || ((paddingY !== 0) ? paddingX : 0); if (!this.isEmpty()) { this.minX -= paddingX; this.maxX += paddingX; this.minY -= paddingY; this.maxY += paddingY; } }; /** * Adds padded frame. (x0, y0) should be strictly less than (x1, y1) * * @param {number} x0 - left X of frame * @param {number} y0 - top Y of frame * @param {number} x1 - right X of frame * @param {number} y1 - bottom Y of frame * @param {number} padX - padding X * @param {number} padY - padding Y */ Bounds.prototype.addFramePad = function addFramePad (x0, y0, x1, y1, padX, padY) { x0 -= padX; y0 -= padY; x1 += padX; y1 += padY; this.minX = this.minX < x0 ? this.minX : x0; this.maxX = this.maxX > x1 ? this.maxX : x1; this.minY = this.minY < y0 ? this.minY : y0; this.maxY = this.maxY > y1 ? this.maxY : y1; }; // _tempDisplayObjectParent = new DisplayObject(); /** * The base class for all objects that are rendered on the screen. * * This is an abstract class and should not be used on its own; rather it should be extended. * * @class * @extends PIXI.utils.EventEmitter * @memberof PIXI */ var DisplayObject = /*@__PURE__*/(function (EventEmitter) { function DisplayObject() { EventEmitter.call(this); this.tempDisplayObjectParent = null; // TODO: need to create Transform from factory /** * World transform and local transform of this object. * This will become read-only later, please do not assign anything there unless you know what are you doing. * * @member {PIXI.Transform} */ this.transform = new math.Transform(); /** * The opacity of the object. * * @member {number} */ this.alpha = 1; /** * The visibility of the object. If false the object will not be drawn, and * the updateTransform function will not be called. * * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually. * * @member {boolean} */ this.visible = true; /** * Can this object be rendered, if false the object will not be drawn but the updateTransform * methods will still be called. * * Only affects recursive calls from parent. You can ask for bounds manually. * * @member {boolean} */ this.renderable = true; /** * The display object container that contains this display object. * * @member {PIXI.Container} * @readonly */ this.parent = null; /** * The multiplied alpha of the displayObject. * * @member {number} * @readonly */ this.worldAlpha = 1; /** * Which index in the children array the display component was before the previous zIndex sort. * Used by containers to help sort objects with the same zIndex, by using previous array index as the decider. * * @member {number} * @protected */ this._lastSortedIndex = 0; /** * The zIndex of the displayObject. * A higher value will mean it will be rendered on top of other displayObjects within the same container. * * @member {number} * @protected */ this._zIndex = 0; /** * The area the filter is applied to. This is used as more of an optimization * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle. * * Also works as an interaction mask. * * @member {?PIXI.Rectangle} */ this.filterArea = null; /** * Sets the filters for the displayObject. * * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. * To remove filters simply set this property to `'null'`. * * @member {?PIXI.Filter[]} */ this.filters = null; this._enabledFilters = null; /** * The bounds object, this is used to calculate and store the bounds of the displayObject. * * @member {PIXI.Bounds} * @protected */ this._bounds = new Bounds(); this._boundsID = 0; this._lastBoundsID = -1; this._boundsRect = null; this._localBoundsRect = null; /** * The original, cached mask of the object. * * @member {PIXI.Graphics|PIXI.Sprite|null} * @protected */ this._mask = null; /** * Fired when this DisplayObject is added to a Container. * * @event PIXI.DisplayObject#added * @param {PIXI.Container} container - The container added to. */ /** * Fired when this DisplayObject is removed from a Container. * * @event PIXI.DisplayObject#removed * @param {PIXI.Container} container - The container removed from. */ /** * If the object has been destroyed via destroy(). If true, it should not be used. * * @member {boolean} * @protected */ this._destroyed = false; /** * used to fast check if a sprite is.. a sprite! * @member {boolean} */ this.isSprite = false; /** * Does any other displayObject use this object as a mask? * @member {boolean} */ this.isMask = false; } if ( EventEmitter ) DisplayObject.__proto__ = EventEmitter; DisplayObject.prototype = Object.create( EventEmitter && EventEmitter.prototype ); DisplayObject.prototype.constructor = DisplayObject; var prototypeAccessors = { _tempDisplayObjectParent: { configurable: true },x: { configurable: true },y: { configurable: true },worldTransform: { configurable: true },localTransform: { configurable: true },position: { configurable: true },scale: { configurable: true },pivot: { configurable: true },skew: { configurable: true },rotation: { configurable: true },angle: { configurable: true },zIndex: { configurable: true },worldVisible: { configurable: true },mask: { configurable: true } }; /** * @protected * @member {PIXI.DisplayObject} */ DisplayObject.mixin = function mixin (source) { // in ES8/ES2017, this would be really easy: // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); // get all the enumerable property keys var keys = Object.keys(source); // loop through properties for (var i = 0; i < keys.length; ++i) { var propertyName = keys[i]; // Set the property using the property descriptor - this works for accessors and normal value properties Object.defineProperty( DisplayObject.prototype, propertyName, Object.getOwnPropertyDescriptor(source, propertyName) ); } }; prototypeAccessors._tempDisplayObjectParent.get = function () { if (this.tempDisplayObjectParent === null) { this.tempDisplayObjectParent = new DisplayObject(); } return this.tempDisplayObjectParent; }; /** * Updates the object transform for rendering. * * TODO - Optimization pass! */ DisplayObject.prototype.updateTransform = function updateTransform () { this._boundsID++; this.transform.updateTransform(this.parent.transform); // multiply the alphas.. this.worldAlpha = this.alpha * this.parent.worldAlpha; }; /** * Recalculates the bounds of the display object. * * Does nothing by default and can be overwritten in a parent class. */ DisplayObject.prototype.calculateBounds = function calculateBounds () { // OVERWRITE; }; /** * Recursively updates transform of all objects from the root to this one * internal function for toLocal() */ DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform () { if (this.parent) { this.parent._recursivePostUpdateTransform(); this.transform.updateTransform(this.parent.transform); } else { this.transform.updateTransform(this._tempDisplayObjectParent.transform); } }; /** * Retrieves the bounds of the displayObject as a rectangle object. * * @param {boolean} [skipUpdate] - Setting to `true` will stop the transforms of the scene graph from * being updated. This means the calculation returned MAY be out of date BUT will give you a * nice performance boost. * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation. * @return {PIXI.Rectangle} The rectangular bounding area. */ DisplayObject.prototype.getBounds = function getBounds (skipUpdate, rect) { if (!skipUpdate) { if (!this.parent) { this.parent = this._tempDisplayObjectParent; this.updateTransform(); this.parent = null; } else { this._recursivePostUpdateTransform(); this.updateTransform(); } } if (this._boundsID !== this._lastBoundsID) { this.calculateBounds(); this._lastBoundsID = this._boundsID; } if (!rect) { if (!this._boundsRect) { this._boundsRect = new math.Rectangle(); } rect = this._boundsRect; } return this._bounds.getRectangle(rect); }; /** * Retrieves the local bounds of the displayObject as a rectangle object. * * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation. * @return {PIXI.Rectangle} The rectangular bounding area. */ DisplayObject.prototype.getLocalBounds = function getLocalBounds (rect) { var transformRef = this.transform; var parentRef = this.parent; this.parent = null; this.transform = this._tempDisplayObjectParent.transform; if (!rect) { if (!this._localBoundsRect) { this._localBoundsRect = new math.Rectangle(); } rect = this._localBoundsRect; } var bounds = this.getBounds(false, rect); this.parent = parentRef; this.transform = transformRef; return bounds; }; /** * Calculates the global position of the display object. * * @param {PIXI.IPoint} position - The world origin to calculate from. * @param {PIXI.IPoint} [point] - A Point object in which to store the value, optional * (otherwise will create a new Point). * @param {boolean} [skipUpdate=false] - Should we skip the update transform. * @return {PIXI.IPoint} A point object representing the position of this object. */ DisplayObject.prototype.toGlobal = function toGlobal (position, point, skipUpdate) { if ( skipUpdate === void 0 ) skipUpdate = false; if (!skipUpdate) { this._recursivePostUpdateTransform(); // this parent check is for just in case the item is a root object. // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) if (!this.parent) { this.parent = this._tempDisplayObjectParent; this.displayObjectUpdateTransform(); this.parent = null; } else { this.displayObjectUpdateTransform(); } } // don't need to update the lot return this.worldTransform.apply(position, point); }; /** * Calculates the local position of the display object relative to another point. * * @param {PIXI.IPoint} position - The world origin to calculate from. * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from. * @param {PIXI.IPoint} [point] - A Point object in which to store the value, optional * (otherwise will create a new Point). * @param {boolean} [skipUpdate=false] - Should we skip the update transform * @return {PIXI.IPoint} A point object representing the position of this object */ DisplayObject.prototype.toLocal = function toLocal (position, from, point, skipUpdate) { if (from) { position = from.toGlobal(position, point, skipUpdate); } if (!skipUpdate) { this._recursivePostUpdateTransform(); // this parent check is for just in case the item is a root object. // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) if (!this.parent) { this.parent = this._tempDisplayObjectParent; this.displayObjectUpdateTransform(); this.parent = null; } else { this.displayObjectUpdateTransform(); } } // simply apply the matrix.. return this.worldTransform.applyInverse(position, point); }; /** * Renders the object using the WebGL renderer. * * @param {PIXI.Renderer} renderer - The renderer. */ DisplayObject.prototype.render = function render (renderer) // eslint-disable-line no-unused-vars { // OVERWRITE; }; /** * Set the parent Container of this DisplayObject. * * @param {PIXI.Container} container - The Container to add this DisplayObject to. * @return {PIXI.Container} The Container that this DisplayObject was added to. */ DisplayObject.prototype.setParent = function setParent (container) { if (!container || !container.addChild) { throw new Error('setParent: Argument must be a Container'); } container.addChild(this); return container; }; /** * Convenience function to set the position, scale, skew and pivot at once. * * @param {number} [x=0] - The X position * @param {number} [y=0] - The Y position * @param {number} [scaleX=1] - The X scale value * @param {number} [scaleY=1] - The Y scale value * @param {number} [rotation=0] - The rotation * @param {number} [skewX=0] - The X skew value * @param {number} [skewY=0] - The Y skew value * @param {number} [pivotX=0] - The X pivot value * @param {number} [pivotY=0] - The Y pivot value * @return {PIXI.DisplayObject} The DisplayObject instance */ DisplayObject.prototype.setTransform = function setTransform (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) { if ( x === void 0 ) x = 0; if ( y === void 0 ) y = 0; if ( scaleX === void 0 ) scaleX = 1; if ( scaleY === void 0 ) scaleY = 1; if ( rotation === void 0 ) rotation = 0; if ( skewX === void 0 ) skewX = 0; if ( skewY === void 0 ) skewY = 0; if ( pivotX === void 0 ) pivotX = 0; if ( pivotY === void 0 ) pivotY = 0; this.position.x = x; this.position.y = y; this.scale.x = !scaleX ? 1 : scaleX; this.scale.y = !scaleY ? 1 : scaleY; this.rotation = rotation; this.skew.x = skewX; this.skew.y = skewY; this.pivot.x = pivotX; this.pivot.y = pivotY; return this; }; /** * Base destroy method for generic display objects. This will automatically * remove the display object from its parent Container as well as remove * all current event listeners and internal references. Do not use a DisplayObject * after calling `destroy()`. * */ DisplayObject.prototype.destroy = function destroy () { if (this.parent) { this.parent.removeChild(this); } this.removeAllListeners(); this.transform = null; this.parent = null; this._bounds = null; this._currentBounds = null; this._mask = null; this.filters = null; this.filterArea = null; this.hitArea = null; this.interactive = false; this.interactiveChildren = false; this._destroyed = true; }; /** * The position of the displayObject on the x axis relative to the local coordinates of the parent. * An alias to position.x * * @member {number} */ prototypeAccessors.x.get = function () { return this.position.x; }; prototypeAccessors.x.set = function (value) // eslint-disable-line require-jsdoc { this.transform.position.x = value; }; /** * The position of the displayObject on the y axis relative to the local coordinates of the parent. * An alias to position.y * * @member {number} */ prototypeAccessors.y.get = function () { return this.position.y; }; prototypeAccessors.y.set = function (value) // eslint-disable-line require-jsdoc { this.transform.position.y = value; }; /** * Current transform of the object based on world (parent) factors. * * @member {PIXI.Matrix} * @readonly */ prototypeAccessors.worldTransform.get = function () { return this.transform.worldTransform; }; /** * Current transform of the object based on local factors: position, scale, other stuff. * * @member {PIXI.Matrix} * @readonly */ prototypeAccessors.localTransform.get = function () { return this.transform.localTransform; }; /** * The coordinate of the object relative to the local coordinates of the parent. * Assignment by value since pixi-v4. * * @member {PIXI.IPoint} */ prototypeAccessors.position.get = function () { return this.transform.position; }; prototypeAccessors.position.set = function (value) // eslint-disable-line require-jsdoc { this.transform.position.copyFrom(value); }; /** * The scale factor of the object. * Assignment by value since pixi-v4. * * @member {PIXI.IPoint} */ prototypeAccessors.scale.get = function () { return this.transform.scale; }; prototypeAccessors.scale.set = function (value) // eslint-disable-line require-jsdoc { this.transform.scale.copyFrom(value); }; /** * The pivot point of the displayObject that it rotates around. * Assignment by value since pixi-v4. * * @member {PIXI.IPoint} */ prototypeAccessors.pivot.get = function () { return this.transform.pivot; }; prototypeAccessors.pivot.set = function (value) // eslint-disable-line require-jsdoc { this.transform.pivot.copyFrom(value); }; /** * The skew factor for the object in radians. * Assignment by value since pixi-v4. * * @member {PIXI.ObservablePoint} */ prototypeAccessors.skew.get = function () { return this.transform.skew; }; prototypeAccessors.skew.set = function (value) // eslint-disable-line require-jsdoc { this.transform.skew.copyFrom(value); }; /** * The rotation of the object in radians. * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. * * @member {number} */ prototypeAccessors.rotation.get = function () { return this.transform.rotation; }; prototypeAccessors.rotation.set = function (value) // eslint-disable-line require-jsdoc { this.transform.rotation = value; }; /** * The angle of the object in degrees. * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. * * @member {number} */ prototypeAccessors.angle.get = function () { return this.transform.rotation * math.RAD_TO_DEG; }; prototypeAccessors.angle.set = function (value) // eslint-disable-line require-jsdoc { this.transform.rotation = value * math.DEG_TO_RAD; }; /** * The zIndex of the displayObject. * If a container has the sortableChildren property set to true, children will be automatically * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, * and thus rendered on top of other displayObjects within the same container. * * @member {number} */ prototypeAccessors.zIndex.get = function () { return this._zIndex; }; prototypeAccessors.zIndex.set = function (value) // eslint-disable-line require-jsdoc { this._zIndex = value; if (this.parent) { this.parent.sortDirty = true; } }; /** * Indicates if the object is globally visible. * * @member {boolean} * @readonly */ prototypeAccessors.worldVisible.get = function () { var item = this; do { if (!item.visible) { return false; } item = item.parent; } while (item); return true; }; /** * Sets a mask for the displayObject. A mask is an object that limits the visibility of an * object to the shape of the mask applied to it. In PixiJS a regular mask must be a * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it * utilities shape clipping. To remove a mask, set this property to `null`. * * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask. * @example * const graphics = new PIXI.Graphics(); * graphics.beginFill(0xFF3300); * graphics.drawRect(50, 250, 100, 100); * graphics.endFill(); * * const sprite = new PIXI.Sprite(texture); * sprite.mask = graphics; * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. * * @member {PIXI.Container|PIXI.MaskData} */ prototypeAccessors.mask.get = function () { return this._mask; }; prototypeAccessors.mask.set = function (value) // eslint-disable-line require-jsdoc { if (this._mask) { var maskObject = this._mask.maskObject || this._mask; maskObject.renderable = true; maskObject.isMask = false; } this._mask = value; if (this._mask) { var maskObject$1 = this._mask.maskObject || this._mask; maskObject$1.renderable = false; maskObject$1.isMask = true; } }; Object.defineProperties( DisplayObject.prototype, prototypeAccessors ); return DisplayObject; }(utils.EventEmitter)); /** * DisplayObject default updateTransform, does not update children of container. * Will crash if there's no parent element. * * @memberof PIXI.DisplayObject# * @function displayObjectUpdateTransform */ DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; function sortChildren(a, b) { if (a.zIndex === b.zIndex) { return a._lastSortedIndex - b._lastSortedIndex; } return a.zIndex - b.zIndex; } /** * A Container represents a collection of display objects. * * It is the base class of all display objects that act as a container for other objects (like Sprites). * *```js * let container = new PIXI.Container(); * container.addChild(sprite); * ``` * * @class * @extends PIXI.DisplayObject * @memberof PIXI */ var Container = /*@__PURE__*/(function (DisplayObject) { function Container() { DisplayObject.call(this); /** * The array of children of this container. * * @member {PIXI.DisplayObject[]} * @readonly */ this.children = []; /** * If set to true, the container will sort its children by zIndex value * when updateTransform() is called, or manually if sortChildren() is called. * * This actually changes the order of elements in the array, so should be treated * as a basic solution that is not performant compared to other solutions, * such as @link https://github.com/pixijs/pixi-display * * Also be aware of that this may not work nicely with the addChildAt() function, * as the zIndex sorting may cause the child to automatically sorted to another position. * * @see PIXI.settings.SORTABLE_CHILDREN * * @member {boolean} */ this.sortableChildren = settings.settings.SORTABLE_CHILDREN; /** * Should children be sorted by zIndex at the next updateTransform call. * Will get automatically set to true if a new child is added, or if a child's zIndex changes. * * @member {boolean} */ this.sortDirty = false; /** * Fired when a DisplayObject is added to this Container. * * @event PIXI.Container#childAdded * @param {PIXI.DisplayObject} child - The child added to the Container. * @param {PIXI.Container} container - The container that added the child. * @param {number} index - The children's index of the added child. */ /** * Fired when a DisplayObject is removed from this Container. * * @event PIXI.DisplayObject#removedFrom * @param {PIXI.DisplayObject} child - The child removed from the Container. * @param {PIXI.Container} container - The container that removed removed the child. * @param {number} index - The former children's index of the removed child */ } if ( DisplayObject ) Container.__proto__ = DisplayObject; Container.prototype = Object.create( DisplayObject && DisplayObject.prototype ); Container.prototype.constructor = Container; var prototypeAccessors = { width: { configurable: true },height: { configurable: true } }; /** * Overridable method that can be used by Container subclasses whenever the children array is modified * * @protected */ Container.prototype.onChildrenChange = function onChildrenChange () { /* empty */ }; /** * Adds one or more children to the container. * * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` * * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container * @return {PIXI.DisplayObject} The first child that was added. */ Container.prototype.addChild = function addChild (child) { var arguments$1 = arguments; var argumentsLength = arguments.length; // if there is only one argument we can bypass looping through the them if (argumentsLength > 1) { // loop through the arguments property and add all children // use it the right way (.length and [i]) so that this function can still be optimized by JS runtimes for (var i = 0; i < argumentsLength; i++) { this.addChild(arguments$1[i]); } } else { // if the child has a parent then lets remove it as PixiJS objects can only exist in one place if (child.parent) { child.parent.removeChild(child); } child.parent = this; this.sortDirty = true; // ensure child transform will be recalculated child.transform._parentID = -1; this.children.push(child); // ensure bounds will be recalculated this._boundsID++; // TODO - lets either do all callbacks or all events.. not both! this.onChildrenChange(this.children.length - 1); this.emit('childAdded', child, this, this.children.length - 1); child.emit('added', this); } return child; }; /** * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown * * @param {PIXI.DisplayObject} child - The child to add * @param {number} index - The index to place the child in * @return {PIXI.DisplayObject} The child that was added. */ Container.prototype.addChildAt = function addChildAt (child, index) { if (index < 0 || index > this.children.length) { throw new Error((child + "addChildAt: The index " + index + " supplied is out of bounds " + (this.children.length))); } if (child.parent) { child.parent.removeChild(child); } child.parent = this; this.sortDirty = true; // ensure child transform will be recalculated child.transform._parentID = -1; this.children.splice(index, 0, child); // ensure bounds will be recalculated this._boundsID++; // TODO - lets either do all callbacks or all events.. not both! this.onChildrenChange(index); child.emit('added', this); this.emit('childAdded', child, this, index); return child; }; /** * Swaps the position of 2 Display Objects within this container. * * @param {PIXI.DisplayObject} child - First display object to swap * @param {PIXI.DisplayObject} child2 - Second display object to swap */ Container.prototype.swapChildren = function swapChildren (child, child2) { if (child === child2) { return; } var index1 = this.getChildIndex(child); var index2 = this.getChildIndex(child2); this.children[index1] = child2; this.children[index2] = child; this.onChildrenChange(index1 < index2 ? index1 : index2); }; /** * Returns the index position of a child DisplayObject instance * * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify * @return {number} The index position of the child display object to identify */ Container.prototype.getChildIndex = function getChildIndex (child) { var index = this.children.indexOf(child); if (index === -1) { throw new Error('The supplied DisplayObject must be a child of the caller'); } return index; }; /** * Changes the position of an existing child in the display object container * * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number * @param {number} index - The resulting index number for the child display object */ Container.prototype.setChildIndex = function setChildIndex (child, index) { if (index < 0 || index >= this.children.length) { throw new Error(("The index " + index + " supplied is out of bounds " + (this.children.length))); } var currentIndex = this.getChildIndex(child); utils.removeItems(this.children, currentIndex, 1); // remove from old position this.children.splice(index, 0, child); // add at new position this.onChildrenChange(index); }; /** * Returns the child at the specified index * * @param {number} index - The index to get the child at * @return {PIXI.DisplayObject} The child at the given index, if any. */ Container.prototype.getChildAt = function getChildAt (index) { if (index < 0 || index >= this.children.length) { throw new Error(("getChildAt: Index (" + index + ") does not exist.")); } return this.children[index]; }; /** * Removes one or more children from the container. * * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove * @return {PIXI.DisplayObject} The first child that was removed. */ Container.prototype.removeChild = function removeChild (child) { var arguments$1 = arguments; var argumentsLength = arguments.length; // if there is only one argument we can bypass looping through the them if (argumentsLength > 1) { // loop through the arguments property and add all children // use it the right way (.length and [i]) so that this function can still be optimized by JS runtimes for (var i = 0; i < argumentsLength; i++) { this.removeChild(arguments$1[i]); } } else { var index = this.children.indexOf(child); if (index === -1) { return null; } child.parent = null; // ensure child transform will be recalculated child.transform._parentID = -1; utils.removeItems(this.children, index, 1); // ensure bounds will be recalculated this._boundsID++; // TODO - lets either do all callbacks or all events.. not both! this.onChildrenChange(index); child.emit('removed', this); this.emit('childRemoved', child, this, index); } return child; }; /** * Removes a child from the specified index position. * * @param {number} index - The index to get the child from * @return {PIXI.DisplayObject} The child that was removed. */ Container.prototype.removeChildAt = function removeChildAt (index) { var child = this.getChildAt(index); // ensure child transform will be recalculated.. child.parent = null; child.transform._parentID = -1; utils.removeItems(this.children, index, 1); // ensure bounds will be recalculated this._boundsID++; // TODO - lets either do all callbacks or all events.. not both! this.onChildrenChange(index); child.emit('removed', this); this.emit('childRemoved', child, this, index); return child; }; /** * Removes all children from this container that are within the begin and end indexes. * * @param {number} [beginIndex=0] - The beginning position. * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. * @returns {PIXI.DisplayObject[]} List of removed children */ Container.prototype.removeChildren = function removeChildren (beginIndex, endIndex) { if ( beginIndex === void 0 ) beginIndex = 0; var begin = beginIndex; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; var removed; if (range > 0 && range <= end) { removed = this.children.splice(begin, range); for (var i = 0; i < removed.length; ++i) { removed[i].parent = null; if (removed[i].transform) { removed[i].transform._parentID = -1; } } this._boundsID++; this.onChildrenChange(beginIndex); for (var i$1 = 0; i$1 < removed.length; ++i$1) { removed[i$1].emit('removed', this); this.emit('childRemoved', removed[i$1], this, i$1); } return removed; } else if (range === 0 && this.children.length === 0) { return []; } throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); }; /** * Sorts children by zIndex. Previous order is mantained for 2 children with the same zIndex. */ Container.prototype.sortChildren = function sortChildren$1 () { var sortRequired = false; for (var i = 0, j = this.children.length; i < j; ++i) { var child = this.children[i]; child._lastSortedIndex = i; if (!sortRequired && child.zIndex !== 0) { sortRequired = true; } } if (sortRequired && this.children.length > 1) { this.children.sort(sortChildren); } this.sortDirty = false; }; /** * Updates the transform on all children of this container for rendering */ Container.prototype.updateTransform = function updateTransform () { if (this.sortableChildren && this.sortDirty) { this.sortChildren(); } this._boundsID++; this.transform.updateTransform(this.parent.transform); // TODO: check render flags, how to process stuff here this.worldAlpha = this.alpha * this.parent.worldAlpha; for (var i = 0, j = this.children.length; i < j; ++i) { var child = this.children[i]; if (child.visible) { child.updateTransform(); } } }; /** * Recalculates the bounds of the container. * */ Container.prototype.calculateBounds = function calculateBounds () { this._bounds.clear(); this._calculateBounds(); for (var i = 0; i < this.children.length; i++) { var child = this.children[i]; if (!child.visible || !child.renderable) { continue; } child.calculateBounds(); // TODO: filter+mask, need to mask both somehow if (child._mask) { var maskObject = child._mask.maskObject || child._mask; maskObject.calculateBounds(); this._bounds.addBoundsMask(child._bounds, maskObject._bounds); } else if (child.filterArea) { this._bounds.addBoundsArea(child._bounds, child.filterArea); } else { this._bounds.addBounds(child._bounds); } } this._lastBoundsID = this._boundsID; }; /** * Recalculates the bounds of the object. Override this to * calculate the bounds of the specific object (not including children). * * @protected */ Container.prototype._calculateBounds = function _calculateBounds () { // FILL IN// }; /** * Renders the object using the WebGL renderer * * @param {PIXI.Renderer} renderer - The renderer */ Container.prototype.render = function render (renderer) { // if the object is not visible or the alpha is 0 then no need to render this element if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { return; } // do a quick check to see if this element has a mask or a filter. if (this._mask || (this.filters && this.filters.length)) { this.renderAdvanced(renderer); } else { this._render(renderer); // simple render children! for (var i = 0, j = this.children.length; i < j; ++i) { this.children[i].render(renderer); } } }; /** * Render the object using the WebGL renderer and advanced features. * * @protected * @param {PIXI.Renderer} renderer - The renderer */ Container.prototype.renderAdvanced = function renderAdvanced (renderer) { renderer.batch.flush(); var filters = this.filters; var mask = this._mask; // push filter first as we need to ensure the stencil buffer is correct for any masking if (filters) { if (!this._enabledFilters) { this._enabledFilters = []; } this._enabledFilters.length = 0; for (var i = 0; i < filters.length; i++) { if (filters[i].enabled) { this._enabledFilters.push(filters[i]); } } if (this._enabledFilters.length) { renderer.filter.push(this, this._enabledFilters); } } if (mask) { renderer.mask.push(this, this._mask); } // add this object to the batch, only rendered if it has a texture. this._render(renderer); // now loop through the children and make sure they get rendered for (var i$1 = 0, j = this.children.length; i$1 < j; i$1++) { this.children[i$1].render(renderer); } renderer.batch.flush(); if (mask) { renderer.mask.pop(this, this._mask); } if (filters && this._enabledFilters && this._enabledFilters.length) { renderer.filter.pop(); } }; /** * To be overridden by the subclasses. * * @protected * @param {PIXI.Renderer} renderer - The renderer */ Container.prototype._render = function _render (renderer) // eslint-disable-line no-unused-vars { // this is where content itself gets rendered... }; /** * Removes all internal references and listeners as well as removes children from the display list. * Do not use a Container after calling `destroy`. * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options * have been set to that value * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy * method called as well. 'options' will be passed on to those calls. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true * Should it destroy the texture of the child sprite * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true * Should it destroy the base texture of the child sprite */ Container.prototype.destroy = function destroy (options) { DisplayObject.prototype.destroy.call(this); this.sortDirty = false; var destroyChildren = typeof options === 'boolean' ? options : options && options.children; var oldChildren = this.removeChildren(0, this.children.length); if (destroyChildren) { for (var i = 0; i < oldChildren.length; ++i) { oldChildren[i].destroy(options); } } }; /** * The width of the Container, setting this will actually modify the scale to achieve the value set * * @member {number} */ prototypeAccessors.width.get = function () { return this.scale.x * this.getLocalBounds().width; }; prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc { var width = this.getLocalBounds().width; if (width !== 0) { this.scale.x = value / width; } else { this.scale.x = 1; } this._width = value; }; /** * The height of the Container, setting this will actually modify the scale to achieve the value set * * @member {number} */ prototypeAccessors.height.get = function () { return this.scale.y * this.getLocalBounds().height; }; prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc { var height = this.getLocalBounds().height; if (height !== 0) { this.scale.y = value / height; } else { this.scale.y = 1; } this._height = value; }; Object.defineProperties( Container.prototype, prototypeAccessors ); return Container; }(DisplayObject)); // performance increase to avoid using call.. (10x faster) Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; exports.Bounds = Bounds; exports.Container = Container; exports.DisplayObject = DisplayObject; },{"@pixi/math":21,"@pixi/settings":31,"@pixi/utils":39}],9:[function(require,module,exports){ /*! * @pixi/extract - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/extract is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var utils = require('@pixi/utils'); var math = require('@pixi/math'); var TEMP_RECT = new math.Rectangle(); var BYTES_PER_PIXEL = 4; /** * This class provides renderer-specific plugins for exporting content from a renderer. * For instance, these plugins can be used for saving an Image, Canvas element or for exporting the raw image data (pixels). * * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property. * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. * @example * // Create a new app (will auto-add extract plugin to renderer) * const app = new PIXI.Application(); * * // Draw a red circle * const graphics = new PIXI.Graphics() * .beginFill(0xFF0000) * .drawCircle(0, 0, 50); * * // Render the graphics as an HTMLImageElement * const image = app.renderer.plugins.extract.image(graphics); * document.body.appendChild(image); * @class * @memberof PIXI */ var Extract = function Extract(renderer) { this.renderer = renderer; /** * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture * * @member {PIXI.Extract} extract * @memberof PIXI.Renderer# * @see PIXI.Extract */ renderer.extract = this; }; /** * Will return a HTML Image of the target * * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture * to convert. If left empty will use the main renderer * @param {string} [format] - Image format, e.g. "image/jpeg" or "image/webp". * @param {number} [quality] - JPEG or Webp compression from 0 to 1. Default is 0.92. * @return {HTMLImageElement} HTML Image of the target */ Extract.prototype.image = function image (target, format, quality) { var image = new Image(); image.src = this.base64(target, format, quality); return image; }; /** * Will return a a base64 encoded string of this target. It works by calling * `Extract.getCanvas` and then running toDataURL on that. * * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture * to convert. If left empty will use the main renderer * @param {string} [format] - Image format, e.g. "image/jpeg" or "image/webp". * @param {number} [quality] - JPEG or Webp compression from 0 to 1. Default is 0.92. * @return {string} A base64 encoded string of the texture. */ Extract.prototype.base64 = function base64 (target, format, quality) { return this.canvas(target).toDataURL(format, quality); }; /** * Creates a Canvas element, renders this target to it and then returns it. * * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture * to convert. If left empty will use the main renderer * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ Extract.prototype.canvas = function canvas (target) { var renderer = this.renderer; var resolution; var frame; var flipY = false; var renderTexture; var generated = false; if (target) { if (target instanceof core.RenderTexture) { renderTexture = target; } else { renderTexture = this.renderer.generateTexture(target); generated = true; } } if (renderTexture) { resolution = renderTexture.baseTexture.resolution; frame = renderTexture.frame; flipY = false; renderer.renderTexture.bind(renderTexture); } else { resolution = this.renderer.resolution; flipY = true; frame = TEMP_RECT; frame.width = this.renderer.width; frame.height = this.renderer.height; renderer.renderTexture.bind(null); } var width = Math.floor((frame.width * resolution) + 1e-4); var height = Math.floor((frame.height * resolution) + 1e-4); var canvasBuffer = new utils.CanvasRenderTarget(width, height, 1); var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); // read pixels to the array var gl = renderer.gl; gl.readPixels( frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels ); // add the pixels to the canvas var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); Extract.arrayPostDivide(webglPixels, canvasData.data); canvasBuffer.context.putImageData(canvasData, 0, 0); // pulling pixels if (flipY) { canvasBuffer.context.scale(1, -1); canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); } if (generated) { renderTexture.destroy(true); } // send the canvas back.. return canvasBuffer.canvas; }; /** * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA * order, with integer values between 0 and 255 (included). * * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture * to convert. If left empty will use the main renderer * @return {Uint8Array} One-dimensional array containing the pixel data of the entire texture */ Extract.prototype.pixels = function pixels (target) { var renderer = this.renderer; var resolution; var frame; var renderTexture; var generated = false; if (target) { if (target instanceof core.RenderTexture) { renderTexture = target; } else { renderTexture = this.renderer.generateTexture(target); generated = true; } } if (renderTexture) { resolution = renderTexture.baseTexture.resolution; frame = renderTexture.frame; // bind the buffer renderer.renderTexture.bind(renderTexture); } else { resolution = renderer.resolution; frame = TEMP_RECT; frame.width = renderer.width; frame.height = renderer.height; renderer.renderTexture.bind(null); } var width = frame.width * resolution; var height = frame.height * resolution; var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); // read pixels to the array var gl = renderer.gl; gl.readPixels( frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels ); if (generated) { renderTexture.destroy(true); } Extract.arrayPostDivide(webglPixels, webglPixels); return webglPixels; }; /** * Destroys the extract * */ Extract.prototype.destroy = function destroy () { this.renderer.extract = null; this.renderer = null; }; /** * Takes premultiplied pixel data and produces regular pixel data * * @private * @param pixels {number[] | Uint8Array | Uint8ClampedArray} array of pixel data * @param out {number[] | Uint8Array | Uint8ClampedArray} output array */ Extract.arrayPostDivide = function arrayPostDivide (pixels, out) { for (var i = 0; i < pixels.length; i += 4) { var alpha = out[i + 3] = pixels[i + 3]; if (alpha !== 0) { out[i] = Math.round(Math.min(pixels[i] * 255.0 / alpha, 255.0)); out[i + 1] = Math.round(Math.min(pixels[i + 1] * 255.0 / alpha, 255.0)); out[i + 2] = Math.round(Math.min(pixels[i + 2] * 255.0 / alpha, 255.0)); } else { out[i] = pixels[i]; out[i + 1] = pixels[i + 1]; out[i + 2] = pixels[i + 2]; } } }; exports.Extract = Extract; },{"@pixi/core":7,"@pixi/math":21,"@pixi/utils":39}],10:[function(require,module,exports){ /*! * @pixi/filter-alpha - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/filter-alpha is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var fragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"; /** * Simplest filter - applies alpha. * * Use this instead of Container's alpha property to avoid visual layering of individual elements. * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. * If elements are not opaque, they will blend with each other anyway. * * Very handy if you want to use common features of all filters: * * 1. Assign a blendMode to this filter, blend all elements inside display object with background. * * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. * * @class * @extends PIXI.Filter * @memberof PIXI.filters */ var AlphaFilter = /*@__PURE__*/(function (Filter) { function AlphaFilter(alpha) { if ( alpha === void 0 ) alpha = 1.0; Filter.call(this, core.defaultVertex, fragment, { uAlpha: 1 }); this.alpha = alpha; } if ( Filter ) AlphaFilter.__proto__ = Filter; AlphaFilter.prototype = Object.create( Filter && Filter.prototype ); AlphaFilter.prototype.constructor = AlphaFilter; var prototypeAccessors = { alpha: { configurable: true } }; /** * Coefficient for alpha multiplication * * @member {number} * @default 1 */ prototypeAccessors.alpha.get = function () { return this.uniforms.uAlpha; }; prototypeAccessors.alpha.set = function (value) // eslint-disable-line require-jsdoc { this.uniforms.uAlpha = value; }; Object.defineProperties( AlphaFilter.prototype, prototypeAccessors ); return AlphaFilter; }(core.Filter)); exports.AlphaFilter = AlphaFilter; },{"@pixi/core":7}],11:[function(require,module,exports){ /*! * @pixi/filter-blur - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/filter-blur is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var settings = require('@pixi/settings'); var vertTemplate = "\n attribute vec2 aVertexPosition;\n\n uniform mat3 projectionMatrix;\n\n uniform float strength;\n\n varying vec2 vBlurTexCoords[%size%];\n\n uniform vec4 inputSize;\n uniform vec4 outputFrame;\n\n vec4 filterVertexPosition( void )\n {\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n }\n\n vec2 filterTextureCoord( void )\n {\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n }\n\n void main(void)\n {\n gl_Position = filterVertexPosition();\n\n vec2 textureCoord = filterTextureCoord();\n %blur%\n }"; function generateBlurVertSource(kernelSize, x) { var halfLength = Math.ceil(kernelSize / 2); var vertSource = vertTemplate; var blurLoop = ''; var template; // let value; if (x) { template = 'vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);'; } else { template = 'vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);'; } for (var i = 0; i < kernelSize; i++) { var blur = template.replace('%index%', i); // value = i; // if(i >= halfLength) // { // value = kernelSize - i - 1; // } blur = blur.replace('%sampleIndex%', ((i - (halfLength - 1)) + ".0")); blurLoop += blur; blurLoop += '\n'; } vertSource = vertSource.replace('%blur%', blurLoop); vertSource = vertSource.replace('%size%', kernelSize); return vertSource; } var GAUSSIAN_VALUES = { 5: [0.153388, 0.221461, 0.250301], 7: [0.071303, 0.131514, 0.189879, 0.214607], 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448], }; var fragTemplate = [ 'varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}' ].join('\n'); function generateBlurFragSource(kernelSize) { var kernel = GAUSSIAN_VALUES[kernelSize]; var halfLength = kernel.length; var fragSource = fragTemplate; var blurLoop = ''; var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; var value; for (var i = 0; i < kernelSize; i++) { var blur = template.replace('%index%', i); value = i; if (i >= halfLength) { value = kernelSize - i - 1; } blur = blur.replace('%value%', kernel[value]); blurLoop += blur; blurLoop += '\n'; } fragSource = fragSource.replace('%blur%', blurLoop); fragSource = fragSource.replace('%size%', kernelSize); return fragSource; } /** * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object. * * @class * @extends PIXI.Filter * @memberof PIXI.filters */ var BlurFilterPass = /*@__PURE__*/(function (Filter) { function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize) { kernelSize = kernelSize || 5; var vertSrc = generateBlurVertSource(kernelSize, horizontal); var fragSrc = generateBlurFragSource(kernelSize); Filter.call( // vertex shader this, vertSrc, // fragment shader fragSrc ); this.horizontal = horizontal; this.resolution = resolution || settings.settings.RESOLUTION; this._quality = 0; this.quality = quality || 4; this.blur = strength || 8; } if ( Filter ) BlurFilterPass.__proto__ = Filter; BlurFilterPass.prototype = Object.create( Filter && Filter.prototype ); BlurFilterPass.prototype.constructor = BlurFilterPass; var prototypeAccessors = { blur: { configurable: true },quality: { configurable: true } }; BlurFilterPass.prototype.apply = function apply (filterManager, input, output, clear) { if (output) { if (this.horizontal) { this.uniforms.strength = (1 / output.width) * (output.width / input.width); } else { this.uniforms.strength = (1 / output.height) * (output.height / input.height); } } else { if (this.horizontal) // eslint-disable-line { this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width); } else { this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line } } // screen space! this.uniforms.strength *= this.strength; this.uniforms.strength /= this.passes; if (this.passes === 1) { filterManager.applyFilter(this, input, output, clear); } else { var renderTarget = filterManager.getFilterTexture(); var renderer = filterManager.renderer; var flip = input; var flop = renderTarget; this.state.blend = false; filterManager.applyFilter(this, flip, flop, true); for (var i = 1; i < this.passes - 1; i++) { renderer.renderTexture.bind(flip, flip.filterFrame); this.uniforms.uSampler = flop; var temp = flop; flop = flip; flip = temp; renderer.shader.bind(this); renderer.geometry.draw(5); } this.state.blend = true; filterManager.applyFilter(this, flop, output, clear); filterManager.returnFilterTexture(renderTarget); } }; /** * Sets the strength of both the blur. * * @member {number} * @default 16 */ prototypeAccessors.blur.get = function () { return this.strength; }; prototypeAccessors.blur.set = function (value) // eslint-disable-line require-jsdoc { this.padding = 1 + (Math.abs(value) * 2); this.strength = value; }; /** * Sets the quality of the blur by modifying the number of passes. More passes means higher * quaility bluring but the lower the performance. * * @member {number} * @default 4 */ prototypeAccessors.quality.get = function () { return this._quality; }; prototypeAccessors.quality.set = function (value) // eslint-disable-line require-jsdoc { this._quality = value; this.passes = value; }; Object.defineProperties( BlurFilterPass.prototype, prototypeAccessors ); return BlurFilterPass; }(core.Filter)); /** * The BlurFilter applies a Gaussian blur to an object. * * The strength of the blur can be set for the x-axis and y-axis separately. * * @class * @extends PIXI.Filter * @memberof PIXI.filters */ var BlurFilter = /*@__PURE__*/(function (Filter) { function BlurFilter(strength, quality, resolution, kernelSize) { Filter.call(this); this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize); this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize); this.resolution = resolution || settings.settings.RESOLUTION; this.quality = quality || 4; this.blur = strength || 8; this.repeatEdgePixels = false; } if ( Filter ) BlurFilter.__proto__ = Filter; BlurFilter.prototype = Object.create( Filter && Filter.prototype ); BlurFilter.prototype.constructor = BlurFilter; var prototypeAccessors = { blur: { configurable: true },quality: { configurable: true },blurX: { configurable: true },blurY: { configurable: true },blendMode: { configurable: true },repeatEdgePixels: { configurable: true } }; /** * Applies the filter. * * @param {PIXI.systems.FilterSystem} filterManager - The manager. * @param {PIXI.RenderTexture} input - The input target. * @param {PIXI.RenderTexture} output - The output target. */ BlurFilter.prototype.apply = function apply (filterManager, input, output, clear) { var xStrength = Math.abs(this.blurXFilter.strength); var yStrength = Math.abs(this.blurYFilter.strength); if (xStrength && yStrength) { var renderTarget = filterManager.getFilterTexture(); this.blurXFilter.apply(filterManager, input, renderTarget, true); this.blurYFilter.apply(filterManager, renderTarget, output, clear); filterManager.returnFilterTexture(renderTarget); } else if (yStrength) { this.blurYFilter.apply(filterManager, input, output, clear); } else { this.blurXFilter.apply(filterManager, input, output, clear); } }; BlurFilter.prototype.updatePadding = function updatePadding () { if (this._repeatEdgePixels) { this.padding = 0; } else { this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; } }; /** * Sets the strength of both the blurX and blurY properties simultaneously * * @member {number} * @default 2 */ prototypeAccessors.blur.get = function () { return this.blurXFilter.blur; }; prototypeAccessors.blur.set = function (value) // eslint-disable-line require-jsdoc { this.blurXFilter.blur = this.blurYFilter.blur = value; this.updatePadding(); }; /** * Sets the number of passes for blur. More passes means higher quaility bluring. * * @member {number} * @default 1 */ prototypeAccessors.quality.get = function () { return this.blurXFilter.quality; }; prototypeAccessors.quality.set = function (value) // eslint-disable-line require-jsdoc { this.blurXFilter.quality = this.blurYFilter.quality = value; }; /** * Sets the strength of the blurX property * * @member {number} * @default 2 */ prototypeAccessors.blurX.get = function () { return this.blurXFilter.blur; }; prototypeAccessors.blurX.set = function (value) // eslint-disable-line require-jsdoc { this.blurXFilter.blur = value; this.updatePadding(); }; /** * Sets the strength of the blurY property * * @member {number} * @default 2 */ prototypeAccessors.blurY.get = function () { return this.blurYFilter.blur; }; prototypeAccessors.blurY.set = function (value) // eslint-disable-line require-jsdoc { this.blurYFilter.blur = value; this.updatePadding(); }; /** * Sets the blendmode of the filter * * @member {number} * @default PIXI.BLEND_MODES.NORMAL */ prototypeAccessors.blendMode.get = function () { return this.blurYFilter.blendMode; }; prototypeAccessors.blendMode.set = function (value) // eslint-disable-line require-jsdoc { this.blurYFilter.blendMode = value; }; /** * If set to true the edge of the target will be clamped * * @member {bool} * @default false */ prototypeAccessors.repeatEdgePixels.get = function () { return this._repeatEdgePixels; }; prototypeAccessors.repeatEdgePixels.set = function (value) { this._repeatEdgePixels = value; this.updatePadding(); }; Object.defineProperties( BlurFilter.prototype, prototypeAccessors ); return BlurFilter; }(core.Filter)); exports.BlurFilter = BlurFilter; exports.BlurFilterPass = BlurFilterPass; },{"@pixi/core":7,"@pixi/settings":31}],12:[function(require,module,exports){ /*! * @pixi/filter-color-matrix - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/filter-color-matrix is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var fragment = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"; /** * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA * color and alpha values of every pixel on your displayObject to produce a result * with a new set of RGBA color and alpha values. It's pretty powerful! * * ```js * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); * container.filters = [colorMatrix]; * colorMatrix.contrast(2); * ``` * @author Clément Chenebault * @class * @extends PIXI.Filter * @memberof PIXI.filters */ var ColorMatrixFilter = /*@__PURE__*/(function (Filter) { function ColorMatrixFilter() { var uniforms = { m: new Float32Array([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]), uAlpha: 1, }; Filter.call(this, core.defaultFilterVertex, fragment, uniforms); this.alpha = 1; } if ( Filter ) ColorMatrixFilter.__proto__ = Filter; ColorMatrixFilter.prototype = Object.create( Filter && Filter.prototype ); ColorMatrixFilter.prototype.constructor = ColorMatrixFilter; var prototypeAccessors = { matrix: { configurable: true },alpha: { configurable: true } }; /** * Transforms current matrix and set the new one * * @param {number[]} matrix - 5x4 matrix * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix (matrix, multiply) { if ( multiply === void 0 ) multiply = false; var newMatrix = matrix; if (multiply) { this._multiply(newMatrix, this.uniforms.m, matrix); newMatrix = this._colorMatrix(newMatrix); } // set the new matrix this.uniforms.m = newMatrix; }; /** * Multiplies two mat5's * * @private * @param {number[]} out - 5x4 matrix the receiving matrix * @param {number[]} a - 5x4 matrix the first operand * @param {number[]} b - 5x4 matrix the second operand * @returns {number[]} 5x4 matrix */ ColorMatrixFilter.prototype._multiply = function _multiply (out, a, b) { // Red Channel out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]); out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]); out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]); out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]); out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4]; // Green Channel out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]); out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]); out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]); out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]); out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9]; // Blue Channel out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]); out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]); out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]); out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]); out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14]; // Alpha Channel out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]); out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]); out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]); out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]); out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19]; return out; }; /** * Create a Float32 Array and normalize the offset component to 0-1 * * @private * @param {number[]} matrix - 5x4 matrix * @return {number[]} 5x4 matrix with all values between 0-1 */ ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix (matrix) { // Create a Float32 Array and normalize the offset component to 0-1 var m = new Float32Array(matrix); m[4] /= 255; m[9] /= 255; m[14] /= 255; m[19] /= 255; return m; }; /** * Adjusts brightness * * @param {number} b - value of the brigthness (0-1, where 0 is black) * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.brightness = function brightness (b, multiply) { var matrix = [ b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Set the matrices in grey scales * * @param {number} scale - value of the grey (0-1, where 0 is black) * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.greyscale = function greyscale (scale, multiply) { var matrix = [ scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Set the black and white matrice. * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite (multiply) { var matrix = [ 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Set the hue property of the color * * @param {number} rotation - in degrees * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.hue = function hue (rotation, multiply) { rotation = (rotation || 0) / 180 * Math.PI; var cosR = Math.cos(rotation); var sinR = Math.sin(rotation); var sqrt = Math.sqrt; /* a good approximation for hue rotation This matrix is far better than the versions with magic luminance constants formerly used here, but also used in the starling framework (flash) and known from this old part of the internet: quasimondo.com/archives/000565.php This new matrix is based on rgb cube rotation in space. Look here for a more descriptive implementation as a shader not a general matrix: https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js This is the source for the code: see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 */ var w = 1 / 3; var sqrW = sqrt(w); // weight is var a00 = cosR + ((1.0 - cosR) * w); var a01 = (w * (1.0 - cosR)) - (sqrW * sinR); var a02 = (w * (1.0 - cosR)) + (sqrW * sinR); var a10 = (w * (1.0 - cosR)) + (sqrW * sinR); var a11 = cosR + (w * (1.0 - cosR)); var a12 = (w * (1.0 - cosR)) - (sqrW * sinR); var a20 = (w * (1.0 - cosR)) - (sqrW * sinR); var a21 = (w * (1.0 - cosR)) + (sqrW * sinR); var a22 = cosR + (w * (1.0 - cosR)); var matrix = [ a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Set the contrast matrix, increase the separation between dark and bright * Increase contrast : shadows darker and highlights brighter * Decrease contrast : bring the shadows up and the highlights down * * @param {number} amount - value of the contrast (0-1) * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.contrast = function contrast (amount, multiply) { var v = (amount || 0) + 1; var o = -0.5 * (v - 1); var matrix = [ v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Set the saturation matrix, increase the separation between colors * Increase saturation : increase contrast, brightness, and sharpness * * @param {number} amount - The saturation amount (0-1) * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.saturate = function saturate (amount, multiply) { if ( amount === void 0 ) amount = 0; var x = (amount * 2 / 3) + 1; var y = ((x - 1) * -0.5); var matrix = [ x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Desaturate image (remove color) * * Call the saturate function * */ ColorMatrixFilter.prototype.desaturate = function desaturate () // eslint-disable-line no-unused-vars { this.saturate(-1); }; /** * Negative image (inverse of classic rgb matrix) * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.negative = function negative (multiply) { var matrix = [ -1, 0, 0, 1, 0, 0, -1, 0, 1, 0, 0, 0, -1, 1, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Sepia image * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.sepia = function sepia (multiply) { var matrix = [ 0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Color motion picture process invented in 1916 (thanks Dominic Szablewski) * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.technicolor = function technicolor (multiply) { var matrix = [ 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Polaroid filter * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.polaroid = function polaroid (multiply) { var matrix = [ 1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Filter who transforms : Red -> Blue and Blue -> Red * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.toBGR = function toBGR (multiply) { var matrix = [ 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.kodachrome = function kodachrome (multiply) { var matrix = [ 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Brown delicious browni filter (thanks Dominic Szablewski) * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.browni = function browni (multiply) { var matrix = [ 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Vintage filter (thanks Dominic Szablewski) * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.vintage = function vintage (multiply) { var matrix = [ 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * We don't know exactly what it does, kind of gradient map, but funny to play with! * * @param {number} desaturation - Tone values. * @param {number} toned - Tone values. * @param {string} lightColor - Tone values, example: `0xFFE580` * @param {string} darkColor - Tone values, example: `0xFFE580` * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.colorTone = function colorTone (desaturation, toned, lightColor, darkColor, multiply) { desaturation = desaturation || 0.2; toned = toned || 0.15; lightColor = lightColor || 0xFFE580; darkColor = darkColor || 0x338000; var lR = ((lightColor >> 16) & 0xFF) / 255; var lG = ((lightColor >> 8) & 0xFF) / 255; var lB = (lightColor & 0xFF) / 255; var dR = ((darkColor >> 16) & 0xFF) / 255; var dG = ((darkColor >> 8) & 0xFF) / 255; var dB = (darkColor & 0xFF) / 255; var matrix = [ 0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Night effect * * @param {number} intensity - The intensity of the night effect. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.night = function night (intensity, multiply) { intensity = intensity || 0.1; var matrix = [ intensity * (-2.0), -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Predator effect * * Erase the current matrix by setting a new indepent one * * @param {number} amount - how much the predator feels his future victim * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.predator = function predator (amount, multiply) { var matrix = [ // row 1 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, // row 2 -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, // row 3 -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, // row 4 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * LSD effect * * Multiply the current matrix * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ ColorMatrixFilter.prototype.lsd = function lsd (multiply) { var matrix = [ 2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, multiply); }; /** * Erase the current matrix by setting the default one * */ ColorMatrixFilter.prototype.reset = function reset () { var matrix = [ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 ]; this._loadMatrix(matrix, false); }; /** * The matrix of the color matrix filter * * @member {number[]} * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] */ prototypeAccessors.matrix.get = function () { return this.uniforms.m; }; prototypeAccessors.matrix.set = function (value) // eslint-disable-line require-jsdoc { this.uniforms.m = value; }; /** * The opacity value to use when mixing the original and resultant colors. * * When the value is 0, the original color is used without modification. * When the value is 1, the result color is used. * When in the range (0, 1) the color is interpolated between the original and result by this amount. * * @member {number} * @default 1 */ prototypeAccessors.alpha.get = function () { return this.uniforms.uAlpha; }; prototypeAccessors.alpha.set = function (value) // eslint-disable-line require-jsdoc { this.uniforms.uAlpha = value; }; Object.defineProperties( ColorMatrixFilter.prototype, prototypeAccessors ); return ColorMatrixFilter; }(core.Filter)); // Americanized alias ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; exports.ColorMatrixFilter = ColorMatrixFilter; },{"@pixi/core":7}],13:[function(require,module,exports){ /*! * @pixi/filter-displacement - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/filter-displacement is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var math = require('@pixi/math'); var vertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n"; var fragment = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n"; /** * The DisplacementFilter class uses the pixel values from the specified texture * (called the displacement map) to perform a displacement of an object. * * You can use this filter to apply all manor of crazy warping effects. * Currently the `r` property of the texture is used to offset the `x` * and the `g` property of the texture is used to offset the `y`. * * The way it works is it uses the values of the displacement map to look up the * correct pixels to output. This means it's not technically moving the original. * Instead, it's starting at the output and asking "which pixel from the original goes here". * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`, * this filter will output the pixel approximately 20 pixels to the right of the original. * * @class * @extends PIXI.Filter * @memberof PIXI.filters */ var DisplacementFilter = /*@__PURE__*/(function (Filter) { function DisplacementFilter(sprite, scale) { var maskMatrix = new math.Matrix(); sprite.renderable = false; Filter.call(this, vertex, fragment, { mapSampler: sprite._texture, filterMatrix: maskMatrix, scale: { x: 1, y: 1 }, rotation: new Float32Array([1, 0, 0, 1]), }); this.maskSprite = sprite; this.maskMatrix = maskMatrix; if (scale === null || scale === undefined) { scale = 20; } /** * scaleX, scaleY for displacements * @member {PIXI.Point} */ this.scale = new math.Point(scale, scale); } if ( Filter ) DisplacementFilter.__proto__ = Filter; DisplacementFilter.prototype = Object.create( Filter && Filter.prototype ); DisplacementFilter.prototype.constructor = DisplacementFilter; var prototypeAccessors = { map: { configurable: true } }; /** * Applies the filter. * * @param {PIXI.systems.FilterSystem} filterManager - The manager. * @param {PIXI.RenderTexture} input - The input target. * @param {PIXI.RenderTexture} output - The output target. * @param {boolean} clear - Should the output be cleared before rendering to it. */ DisplacementFilter.prototype.apply = function apply (filterManager, input, output, clear) { // fill maskMatrix with _normalized sprite texture coords_ this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); this.uniforms.scale.x = this.scale.x; this.uniforms.scale.y = this.scale.y; // Extract rotation from world transform var wt = this.maskSprite.transform.worldTransform; var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b)); var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d)); if (lenX !== 0 && lenY !== 0) { this.uniforms.rotation[0] = wt.a / lenX; this.uniforms.rotation[1] = wt.b / lenX; this.uniforms.rotation[2] = wt.c / lenY; this.uniforms.rotation[3] = wt.d / lenY; } // draw the filter... filterManager.applyFilter(this, input, output, clear); }; /** * The texture used for the displacement map. Must be power of 2 sized texture. * * @member {PIXI.Texture} */ prototypeAccessors.map.get = function () { return this.uniforms.mapSampler; }; prototypeAccessors.map.set = function (value) // eslint-disable-line require-jsdoc { this.uniforms.mapSampler = value; }; Object.defineProperties( DisplacementFilter.prototype, prototypeAccessors ); return DisplacementFilter; }(core.Filter)); exports.DisplacementFilter = DisplacementFilter; },{"@pixi/core":7,"@pixi/math":21}],14:[function(require,module,exports){ /*! * @pixi/filter-drop-shadow - v3.1.0 * Compiled Wed, 11 Mar 2020 20:38:18 UTC * * @pixi/filter-drop-shadow is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var filterKawaseBlur = require('@pixi/filter-kawase-blur'); var core = require('@pixi/core'); var settings = require('@pixi/settings'); var math = require('@pixi/math'); var utils = require('@pixi/utils'); var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; var fragment = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform vec3 color;\n\nuniform vec2 shift;\nuniform vec4 inputSize;\n\nvoid main(void){\n vec4 sample = texture2D(uSampler, vTextureCoord - shift * inputSize.zw);\n\n // Premultiply alpha\n sample.rgb = color.rgb * sample.a;\n\n // alpha user alpha\n sample *= alpha;\n\n gl_FragColor = sample;\n}"; /** * Drop shadow filter.
* ![original](../tools/screenshots/dist/original.png)![filter](../tools/screenshots/dist/drop-shadow.png) * @class * @extends PIXI.Filter * @memberof PIXI.filters * @see {@link https://www.npmjs.com/package/@pixi/filter-drop-shadow|@pixi/filter-drop-shadow} * @see {@link https://www.npmjs.com/package/pixi-filters|pixi-filters} * @param {object} [options] Filter options * @param {number} [options.rotation=45] The angle of the shadow in degrees. * @param {number} [options.distance=5] Distance of shadow * @param {number} [options.color=0x000000] Color of the shadow * @param {number} [options.alpha=0.5] Alpha of the shadow * @param {number} [options.shadowOnly=false] Whether render shadow only * @param {number} [options.blur=2] - Sets the strength of the Blur properties simultaneously * @param {number} [options.quality=3] - The quality of the Blur filter. * @param {number[]} [options.kernels=null] - The kernels of the Blur filter. * @param {number|number[]|PIXI.Point} [options.pixelSize=1] - the pixelSize of the Blur filter. * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution of the Blur filter. */ var DropShadowFilter = /*@__PURE__*/(function (Filter) { function DropShadowFilter(options) { // Fallback support for ctor: (rotation, distance, blur, color, alpha) if (options && options.constructor !== Object) { // eslint-disable-next-line no-console console.warn('DropShadowFilter now uses options instead of (rotation, distance, blur, color, alpha)'); options = { rotation: options }; if (arguments[1] !== undefined) { options.distance = arguments[1]; } if (arguments[2] !== undefined) { options.blur = arguments[2]; } if (arguments[3] !== undefined) { options.color = arguments[3]; } if (arguments[4] !== undefined) { options.alpha = arguments[4]; } } options = Object.assign({ rotation: 45, distance: 5, color: 0x000000, alpha: 0.5, shadowOnly: false, kernels: null, blur: 2, quality: 3, pixelSize: 1, resolution: settings.settings.RESOLUTION, }, options); Filter.call(this); var kernels = options.kernels; var blur = options.blur; var quality = options.quality; var pixelSize = options.pixelSize; var resolution = options.resolution; this._tintFilter = new Filter(vertex, fragment); this._tintFilter.uniforms.color = new Float32Array(4); this._tintFilter.uniforms.shift = new math.Point(); this._tintFilter.resolution = resolution; this._blurFilter = kernels ? new filterKawaseBlur.KawaseBlurFilter(kernels) : new filterKawaseBlur.KawaseBlurFilter(blur, quality); this.pixelSize = pixelSize; this.resolution = resolution; var shadowOnly = options.shadowOnly; var rotation = options.rotation; var distance = options.distance; var alpha = options.alpha; var color = options.color; this.shadowOnly = shadowOnly; this.rotation = rotation; this.distance = distance; this.alpha = alpha; this.color = color; this._updatePadding(); } if ( Filter ) DropShadowFilter.__proto__ = Filter; DropShadowFilter.prototype = Object.create( Filter && Filter.prototype ); DropShadowFilter.prototype.constructor = DropShadowFilter; var prototypeAccessors = { resolution: { configurable: true },distance: { configurable: true },rotation: { configurable: true },alpha: { configurable: true },color: { configurable: true },kernels: { configurable: true },blur: { configurable: true },quality: { configurable: true },pixelSize: { configurable: true } }; DropShadowFilter.prototype.apply = function apply (filterManager, input, output, clear) { var target = filterManager.getFilterTexture(); this._tintFilter.apply(filterManager, input, target, 1); this._blurFilter.apply(filterManager, target, output, clear); if (this.shadowOnly !== true) { filterManager.applyFilter(this, input, output, 0); } filterManager.returnFilterTexture(target); }; /** * Recalculate the proper padding amount. * @private */ DropShadowFilter.prototype._updatePadding = function _updatePadding () { this.padding = this.distance + (this.blur * 2); }; /** * Update the transform matrix of offset angle. * @private */ DropShadowFilter.prototype._updateShift = function _updateShift () { this._tintFilter.uniforms.shift.set( this.distance * Math.cos(this.angle), this.distance * Math.sin(this.angle) ); }; /** * The resolution of the filter. * * @member {number} * @default PIXI.settings.RESOLUTION */ prototypeAccessors.resolution.get = function () { return this._resolution; }; prototypeAccessors.resolution.set = function (value) { this._resolution = value; if (this._tintFilter) { this._tintFilter.resolution = value; } if (this._blurFilter) { this._blurFilter.resolution = value; } }; /** * Distance offset of the shadow * @member {number} * @default 5 */ prototypeAccessors.distance.get = function () { return this._distance; }; prototypeAccessors.distance.set = function (value) { this._distance = value; this._updatePadding(); this._updateShift(); }; /** * The angle of the shadow in degrees * @member {number} * @default 2 */ prototypeAccessors.rotation.get = function () { return this.angle / math.DEG_TO_RAD; }; prototypeAccessors.rotation.set = function (value) { this.angle = value * math.DEG_TO_RAD; this._updateShift(); }; /** * The alpha of the shadow * @member {number} * @default 1 */ prototypeAccessors.alpha.get = function () { return this._tintFilter.uniforms.alpha; }; prototypeAccessors.alpha.set = function (value) { this._tintFilter.uniforms.alpha = value; }; /** * The color of the shadow. * @member {number} * @default 0x000000 */ prototypeAccessors.color.get = function () { return utils.rgb2hex(this._tintFilter.uniforms.color); }; prototypeAccessors.color.set = function (value) { utils.hex2rgb(value, this._tintFilter.uniforms.color); }; /** * Sets the kernels of the Blur Filter * * @member {number[]} */ prototypeAccessors.kernels.get = function () { return this._blurFilter.kernels; }; prototypeAccessors.kernels.set = function (value) { this._blurFilter.kernels = value; }; /** * The blur of the shadow * @member {number} * @default 2 */ prototypeAccessors.blur.get = function () { return this._blurFilter.blur; }; prototypeAccessors.blur.set = function (value) { this._blurFilter.blur = value; this._updatePadding(); }; /** * Sets the quality of the Blur Filter * * @member {number} * @default 4 */ prototypeAccessors.quality.get = function () { return this._blurFilter.quality; }; prototypeAccessors.quality.set = function (value) { this._blurFilter.quality = value; }; /** * Sets the pixelSize of the Kawase Blur filter * * @member {number|number[]|PIXI.Point} * @default 1 */ prototypeAccessors.pixelSize.get = function () { return this._blurFilter.pixelSize; }; prototypeAccessors.pixelSize.set = function (value) { this._blurFilter.pixelSize = value; }; Object.defineProperties( DropShadowFilter.prototype, prototypeAccessors ); return DropShadowFilter; }(core.Filter)); exports.DropShadowFilter = DropShadowFilter; },{"@pixi/core":7,"@pixi/filter-kawase-blur":16,"@pixi/math":21,"@pixi/settings":31,"@pixi/utils":39}],15:[function(require,module,exports){ /*! * @pixi/filter-fxaa - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/filter-fxaa is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var vertex = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputPixel;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n"; var fragment = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputPixel;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n"; /** * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL. * * @see https://github.com/mitsuhiko/webgl-meincraft * * @class * @extends PIXI.Filter * @memberof PIXI.filters * */ var FXAAFilter = /*@__PURE__*/(function (Filter) { function FXAAFilter() { // TODO - needs work Filter.call(this, vertex, fragment); } if ( Filter ) FXAAFilter.__proto__ = Filter; FXAAFilter.prototype = Object.create( Filter && Filter.prototype ); FXAAFilter.prototype.constructor = FXAAFilter; return FXAAFilter; }(core.Filter)); exports.FXAAFilter = FXAAFilter; },{"@pixi/core":7}],16:[function(require,module,exports){ /*! * @pixi/filter-kawase-blur - v3.1.0 * Compiled Wed, 11 Mar 2020 20:38:18 UTC * * @pixi/filter-kawase-blur is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var math = require('@pixi/math'); var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; var fragment = "\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample top right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}"; var fragmentClamp = "\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample top right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}\n"; /** * A much faster blur than Gaussian blur, but more complicated to use.
* ![original](../tools/screenshots/dist/original.png)![filter](../tools/screenshots/dist/kawase-blur.png) * * @see https://software.intel.com/en-us/blogs/2014/07/15/an-investigation-of-fast-real-time-gpu-based-image-blur-algorithms * @class * @extends PIXI.Filter * @memberof PIXI.filters * @see {@link https://www.npmjs.com/package/@pixi/filter-kawase-blur|@pixi/filter-kawase-blur} * @see {@link https://www.npmjs.com/package/pixi-filters|pixi-filters} * @param {number|number[]} [blur=4] - The blur of the filter. Should be greater than `0`. If * value is an Array, setting kernels. * @param {number} [quality=3] - The quality of the filter. Should be an integer greater than `1`. * @param {boolean} [clamp=false] - Clamp edges, useful for removing dark edges * from fullscreen filters or bleeding to the edge of filterArea. */ var KawaseBlurFilter = /*@__PURE__*/(function (Filter) { function KawaseBlurFilter(blur, quality, clamp) { if ( blur === void 0 ) blur = 4; if ( quality === void 0 ) quality = 3; if ( clamp === void 0 ) clamp = false; Filter.call(this, vertex, clamp ? fragmentClamp : fragment); this.uniforms.uOffset = new Float32Array(2); this._pixelSize = new math.Point(); this.pixelSize = 1; this._clamp = clamp; this._kernels = null; // if `blur` is array , as kernels if (Array.isArray(blur)) { this.kernels = blur; } else { this._blur = blur; this.quality = quality; } } if ( Filter ) KawaseBlurFilter.__proto__ = Filter; KawaseBlurFilter.prototype = Object.create( Filter && Filter.prototype ); KawaseBlurFilter.prototype.constructor = KawaseBlurFilter; var prototypeAccessors = { kernels: { configurable: true },clamp: { configurable: true },pixelSize: { configurable: true },quality: { configurable: true },blur: { configurable: true } }; /** * Overrides apply * @private */ KawaseBlurFilter.prototype.apply = function apply (filterManager, input, output, clear) { var uvX = this.pixelSize.x / input._frame.width; var uvY = this.pixelSize.y / input._frame.height; var offset; if (this._quality === 1 || this._blur === 0) { offset = this._kernels[0] + 0.5; this.uniforms.uOffset[0] = offset * uvX; this.uniforms.uOffset[1] = offset * uvY; filterManager.applyFilter(this, input, output, clear); } else { var renderTarget = filterManager.getFilterTexture(); var source = input; var target = renderTarget; var tmp; var last = this._quality - 1; for (var i = 0; i < last; i++) { offset = this._kernels[i] + 0.5; this.uniforms.uOffset[0] = offset * uvX; this.uniforms.uOffset[1] = offset * uvY; filterManager.applyFilter(this, source, target, 1); tmp = source; source = target; target = tmp; } offset = this._kernels[last] + 0.5; this.uniforms.uOffset[0] = offset * uvX; this.uniforms.uOffset[1] = offset * uvY; filterManager.applyFilter(this, source, output, clear); filterManager.returnFilterTexture(renderTarget); } }; /** * Auto generate kernels by blur & quality * @private */ KawaseBlurFilter.prototype._generateKernels = function _generateKernels () { var blur = this._blur; var quality = this._quality; var kernels = [ blur ]; if (blur > 0) { var k = blur; var step = blur / quality; for (var i = 1; i < quality; i++) { k -= step; kernels.push(k); } } this._kernels = kernels; }; /** * The kernel size of the blur filter, for advanced usage. * * @member {number[]} * @default [0] */ prototypeAccessors.kernels.get = function () { return this._kernels; }; prototypeAccessors.kernels.set = function (value) { if (Array.isArray(value) && value.length > 0) { this._kernels = value; this._quality = value.length; this._blur = Math.max.apply(Math, value); } else { // if value is invalid , set default value this._kernels = [0]; this._quality = 1; } }; /** * Get the if the filter is clampped. * * @readonly * @member {boolean} * @default false */ prototypeAccessors.clamp.get = function () { return this._clamp; }; /** * Sets the pixel size of the filter. Large size is blurrier. For advanced usage. * * @member {PIXI.Point|number[]} * @default [1, 1] */ prototypeAccessors.pixelSize.set = function (value) { if (typeof value === 'number') { this._pixelSize.x = value; this._pixelSize.y = value; } else if (Array.isArray(value)) { this._pixelSize.x = value[0]; this._pixelSize.y = value[1]; } else if (value instanceof math.Point) { this._pixelSize.x = value.x; this._pixelSize.y = value.y; } else { // if value is invalid , set default value this._pixelSize.x = 1; this._pixelSize.y = 1; } }; prototypeAccessors.pixelSize.get = function () { return this._pixelSize; }; /** * The quality of the filter, integer greater than `1`. * * @member {number} * @default 3 */ prototypeAccessors.quality.get = function () { return this._quality; }; prototypeAccessors.quality.set = function (value) { this._quality = Math.max(1, Math.round(value)); this._generateKernels(); }; /** * The amount of blur, value greater than `0`. * * @member {number} * @default 4 */ prototypeAccessors.blur.get = function () { return this._blur; }; prototypeAccessors.blur.set = function (value) { this._blur = value; this._generateKernels(); }; Object.defineProperties( KawaseBlurFilter.prototype, prototypeAccessors ); return KawaseBlurFilter; }(core.Filter)); exports.KawaseBlurFilter = KawaseBlurFilter; },{"@pixi/core":7,"@pixi/math":21}],17:[function(require,module,exports){ /*! * @pixi/filter-noise - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/filter-noise is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var fragment = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"; /** * @author Vico @vicocotea * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js */ /** * A Noise effect filter. * * @class * @extends PIXI.Filter * @memberof PIXI.filters */ var NoiseFilter = /*@__PURE__*/(function (Filter) { function NoiseFilter(noise, seed) { if ( noise === void 0 ) noise = 0.5; if ( seed === void 0 ) seed = Math.random(); Filter.call(this, core.defaultFilterVertex, fragment, { uNoise: 0, uSeed: 0, }); this.noise = noise; this.seed = seed; } if ( Filter ) NoiseFilter.__proto__ = Filter; NoiseFilter.prototype = Object.create( Filter && Filter.prototype ); NoiseFilter.prototype.constructor = NoiseFilter; var prototypeAccessors = { noise: { configurable: true },seed: { configurable: true } }; /** * The amount of noise to apply, this value should be in the range (0, 1]. * * @member {number} * @default 0.5 */ prototypeAccessors.noise.get = function () { return this.uniforms.uNoise; }; prototypeAccessors.noise.set = function (value) // eslint-disable-line require-jsdoc { this.uniforms.uNoise = value; }; /** * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. * * @member {number} */ prototypeAccessors.seed.get = function () { return this.uniforms.uSeed; }; prototypeAccessors.seed.set = function (value) // eslint-disable-line require-jsdoc { this.uniforms.uSeed = value; }; Object.defineProperties( NoiseFilter.prototype, prototypeAccessors ); return NoiseFilter; }(core.Filter)); exports.NoiseFilter = NoiseFilter; },{"@pixi/core":7}],18:[function(require,module,exports){ /*! * @pixi/graphics - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/graphics is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var math = require('@pixi/math'); var utils = require('@pixi/utils'); var constants = require('@pixi/constants'); var display = require('@pixi/display'); /** * Graphics curves resolution settings. If `adaptive` flag is set to `true`, * the resolution is calculated based on the curve's length to ensure better visual quality. * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. * * @static * @constant * @memberof PIXI * @name GRAPHICS_CURVES * @type {object} * @property {boolean} adaptive=false - flag indicating if the resolution should be adaptive * @property {number} maxLength=10 - maximal length of a single segment of the curve (if adaptive = false, ignored) * @property {number} minSegments=8 - minimal number of segments in the curve (if adaptive = false, ignored) * @property {number} maxSegments=2048 - maximal number of segments in the curve (if adaptive = false, ignored) */ var GRAPHICS_CURVES = { adaptive: true, maxLength: 10, minSegments: 8, maxSegments: 2048, _segmentsCount: function _segmentsCount(length, defaultSegments) { if ( defaultSegments === void 0 ) defaultSegments = 20; if (!this.adaptive || !length || Number.isNaN(length)) { return defaultSegments; } var result = Math.ceil(length / this.maxLength); if (result < this.minSegments) { result = this.minSegments; } else if (result > this.maxSegments) { result = this.maxSegments; } return result; }, }; /** * Fill style object for Graphics. * * @class * @memberof PIXI */ var FillStyle = function FillStyle() { this.reset(); }; /** * Clones the object * * @return {PIXI.FillStyle} */ FillStyle.prototype.clone = function clone () { var obj = new FillStyle(); obj.color = this.color; obj.alpha = this.alpha; obj.texture = this.texture; obj.matrix = this.matrix; obj.visible = this.visible; return obj; }; /** * Reset */ FillStyle.prototype.reset = function reset () { /** * The hex color value used when coloring the Graphics object. * * @member {number} * @default 1 */ this.color = 0xFFFFFF; /** * The alpha value used when filling the Graphics object. * * @member {number} * @default 1 */ this.alpha = 1; /** * The texture to be used for the fill. * * @member {string} * @default 0 */ this.texture = core.Texture.WHITE; /** * The transform aplpied to the texture. * * @member {string} * @default 0 */ this.matrix = null; /** * If the current fill is visible. * * @member {boolean} * @default false */ this.visible = false; }; /** * Destroy and don't use after this */ FillStyle.prototype.destroy = function destroy () { this.texture = null; this.matrix = null; }; /** * Builds a polygon to draw * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines */ var buildPoly = { build: function build(graphicsData) { graphicsData.points = graphicsData.shape.points.slice(); }, triangulate: function triangulate(graphicsData, graphicsGeometry) { var points = graphicsData.points; var holes = graphicsData.holes; var verts = graphicsGeometry.points; var indices = graphicsGeometry.indices; if (points.length >= 6) { var holeArray = []; // Process holes.. for (var i = 0; i < holes.length; i++) { var hole = holes[i]; holeArray.push(points.length / 2); points = points.concat(hole.points); } // sort color var triangles = utils.earcut(points, holeArray, 2); if (!triangles) { return; } var vertPos = verts.length / 2; for (var i$1 = 0; i$1 < triangles.length; i$1 += 3) { indices.push(triangles[i$1] + vertPos); indices.push(triangles[i$1 + 1] + vertPos); indices.push(triangles[i$1 + 2] + vertPos); } for (var i$2 = 0; i$2 < points.length; i$2++) { verts.push(points[i$2]); } } }, }; /** * Builds a circle to draw * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines */ var buildCircle = { build: function build(graphicsData) { // need to convert points to a nice regular data var circleData = graphicsData.shape; var points = graphicsData.points; var x = circleData.x; var y = circleData.y; var width; var height; points.length = 0; // TODO - bit hacky?? if (graphicsData.type === math.SHAPES.CIRC) { width = circleData.radius; height = circleData.radius; } else { width = circleData.width; height = circleData.height; } if (width === 0 || height === 0) { return; } var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); totalSegs /= 2.3; var seg = (Math.PI * 2) / totalSegs; for (var i = 0; i < totalSegs - 0.5; i++) { points.push( x + (Math.sin(-seg * i) * width), y + (Math.cos(-seg * i) * height) ); } points.push( points[0], points[1] ); }, triangulate: function triangulate(graphicsData, graphicsGeometry) { var points = graphicsData.points; var verts = graphicsGeometry.points; var indices = graphicsGeometry.indices; var vertPos = verts.length / 2; var center = vertPos; verts.push(graphicsData.shape.x, graphicsData.shape.y); for (var i = 0; i < points.length; i += 2) { verts.push(points[i], points[i + 1]); // add some uvs indices.push(vertPos++, center, vertPos); } }, }; /** * Builds a rectangle to draw * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines */ var buildRectangle = { build: function build(graphicsData) { // --- // // need to convert points to a nice regular data // var rectData = graphicsData.shape; var x = rectData.x; var y = rectData.y; var width = rectData.width; var height = rectData.height; var points = graphicsData.points; points.length = 0; points.push(x, y, x + width, y, x + width, y + height, x, y + height); }, triangulate: function triangulate(graphicsData, graphicsGeometry) { var points = graphicsData.points; var verts = graphicsGeometry.points; var vertPos = verts.length / 2; verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]); graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3); }, }; /** * Builds a rounded rectangle to draw * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines */ var buildRoundedRectangle = { build: function build(graphicsData) { var rrectData = graphicsData.shape; var points = graphicsData.points; var x = rrectData.x; var y = rrectData.y; var width = rrectData.width; var height = rrectData.height; var radius = rrectData.radius; points.length = 0; quadraticBezierCurve(x, y + radius, x, y, x + radius, y, points); quadraticBezierCurve(x + width - radius, y, x + width, y, x + width, y + radius, points); quadraticBezierCurve(x + width, y + height - radius, x + width, y + height, x + width - radius, y + height, points); quadraticBezierCurve(x + radius, y + height, x, y + height, x, y + height - radius, points); // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. // TODO - fix this properly, this is not very elegant.. but it works for now. }, triangulate: function triangulate(graphicsData, graphicsGeometry) { var points = graphicsData.points; var verts = graphicsGeometry.points; var indices = graphicsGeometry.indices; var vecPos = verts.length / 2; var triangles = utils.earcut(points, null, 2); for (var i = 0, j = triangles.length; i < j; i += 3) { indices.push(triangles[i] + vecPos); // indices.push(triangles[i] + vecPos); indices.push(triangles[i + 1] + vecPos); // indices.push(triangles[i + 2] + vecPos); indices.push(triangles[i + 2] + vecPos); } for (var i$1 = 0, j$1 = points.length; i$1 < j$1; i$1++) { verts.push(points[i$1], points[++i$1]); } }, }; /** * Calculate a single point for a quadratic bezier curve. * Utility function used by quadraticBezierCurve. * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {number} n1 - first number * @param {number} n2 - second number * @param {number} perc - percentage * @return {number} the result * */ function getPt(n1, n2, perc) { var diff = n2 - n1; return n1 + (diff * perc); } /** * Calculate the points for a quadratic bezier curve. (helper function..) * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {number} fromX - Origin point x * @param {number} fromY - Origin point x * @param {number} cpX - Control point x * @param {number} cpY - Control point y * @param {number} toX - Destination point x * @param {number} toY - Destination point y * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. * @return {number[]} an array of points */ function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) { if ( out === void 0 ) out = []; var n = 20; var points = out; var xa = 0; var ya = 0; var xb = 0; var yb = 0; var x = 0; var y = 0; for (var i = 0, j = 0; i <= n; ++i) { j = i / n; // The Green Line xa = getPt(fromX, cpX, j); ya = getPt(fromY, cpY, j); xb = getPt(cpX, toX, j); yb = getPt(cpY, toY, j); // The Black Dot x = getPt(xa, xb, j); y = getPt(ya, yb, j); points.push(x, y); } return points; } /** * Builds a line to draw * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output */ function buildLine(graphicsData, graphicsGeometry) { if (graphicsData.lineStyle.native) { buildNativeLine(graphicsData, graphicsGeometry); } else { buildNonNativeLine(graphicsData, graphicsGeometry); } } /** * Builds a line to draw using the polygon method. * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output */ function buildNonNativeLine(graphicsData, graphicsGeometry) { var shape = graphicsData.shape; var points = graphicsData.points || shape.points.slice(); var eps = graphicsGeometry.closePointEps; if (points.length === 0) { return; } // if the line width is an odd number add 0.5 to align to a whole pixel // commenting this out fixes #711 and #1620 // if (graphicsData.lineWidth%2) // { // for (i = 0; i < points.length; i++) // { // points[i] += 0.5; // } // } var style = graphicsData.lineStyle; // get first and last point.. figure out the middle! var firstPoint = new math.Point(points[0], points[1]); var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); var closedShape = shape.type !== math.SHAPES.POLY || shape.closeStroke; var closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps && Math.abs(firstPoint.y - lastPoint.y) < eps; // if the first point is the last point - gonna have issues :) if (closedShape) { // need to clone as we are going to slightly modify the shape.. points = points.slice(); if (closedPath) { points.pop(); points.pop(); lastPoint.set(points[points.length - 2], points[points.length - 1]); } var midPointX = lastPoint.x + ((firstPoint.x - lastPoint.x) * 0.5); var midPointY = lastPoint.y + ((firstPoint.y - lastPoint.y) * 0.5); points.unshift(midPointX, midPointY); points.push(midPointX, midPointY); } var verts = graphicsGeometry.points; var length = points.length / 2; var indexCount = points.length; var indexStart = verts.length / 2; // DRAW the Line var width = style.width / 2; // sort color var p1x = points[0]; var p1y = points[1]; var p2x = points[2]; var p2y = points[3]; var p3x = 0; var p3y = 0; var perpx = -(p1y - p2y); var perpy = p1x - p2x; var perp2x = 0; var perp2y = 0; var perp3x = 0; var perp3y = 0; var dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); perpx /= dist; perpy /= dist; perpx *= width; perpy *= width; var ratio = style.alignment;// 0.5; var r1 = (1 - ratio) * 2; var r2 = ratio * 2; // start verts.push( p1x - (perpx * r1), p1y - (perpy * r1)); verts.push( p1x + (perpx * r2), p1y + (perpy * r2)); for (var i = 1; i < length - 1; ++i) { p1x = points[(i - 1) * 2]; p1y = points[((i - 1) * 2) + 1]; p2x = points[i * 2]; p2y = points[(i * 2) + 1]; p3x = points[(i + 1) * 2]; p3y = points[((i + 1) * 2) + 1]; perpx = -(p1y - p2y); perpy = p1x - p2x; dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); perpx /= dist; perpy /= dist; perpx *= width; perpy *= width; perp2x = -(p2y - p3y); perp2y = p2x - p3x; dist = Math.sqrt((perp2x * perp2x) + (perp2y * perp2y)); perp2x /= dist; perp2y /= dist; perp2x *= width; perp2y *= width; var a1 = (-perpy + p1y) - (-perpy + p2y); var b1 = (-perpx + p2x) - (-perpx + p1x); var c1 = ((-perpx + p1x) * (-perpy + p2y)) - ((-perpx + p2x) * (-perpy + p1y)); var a2 = (-perp2y + p3y) - (-perp2y + p2y); var b2 = (-perp2x + p2x) - (-perp2x + p3x); var c2 = ((-perp2x + p3x) * (-perp2y + p2y)) - ((-perp2x + p2x) * (-perp2y + p3y)); var denom = (a1 * b2) - (a2 * b1); if (Math.abs(denom) < 0.1) { denom += 10.1; verts.push( p2x - (perpx * r1), p2y - (perpy * r1)); verts.push( p2x + (perpx * r2), p2y + (perpy * r2)); continue; } var px = ((b1 * c2) - (b2 * c1)) / denom; var py = ((a2 * c1) - (a1 * c2)) / denom; var pdist = ((px - p2x) * (px - p2x)) + ((py - p2y) * (py - p2y)); if (pdist > (196 * width * width)) { perp3x = perpx - perp2x; perp3y = perpy - perp2y; dist = Math.sqrt((perp3x * perp3x) + (perp3y * perp3y)); perp3x /= dist; perp3y /= dist; perp3x *= width; perp3y *= width; verts.push(p2x - (perp3x * r1), p2y - (perp3y * r1)); verts.push(p2x + (perp3x * r2), p2y + (perp3y * r2)); verts.push(p2x - (perp3x * r2 * r1), p2y - (perp3y * r1)); indexCount++; } else { verts.push(p2x + ((px - p2x) * r1), p2y + ((py - p2y) * r1)); verts.push(p2x - ((px - p2x) * r2), p2y - ((py - p2y) * r2)); } } p1x = points[(length - 2) * 2]; p1y = points[((length - 2) * 2) + 1]; p2x = points[(length - 1) * 2]; p2y = points[((length - 1) * 2) + 1]; perpx = -(p1y - p2y); perpy = p1x - p2x; dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); perpx /= dist; perpy /= dist; perpx *= width; perpy *= width; verts.push(p2x - (perpx * r1), p2y - (perpy * r1)); verts.push(p2x + (perpx * r2), p2y + (perpy * r2)); var indices = graphicsGeometry.indices; // indices.push(indexStart); for (var i$1 = 0; i$1 < indexCount - 2; ++i$1) { indices.push(indexStart, indexStart + 1, indexStart + 2); indexStart++; } } /** * Builds a line to draw using the gl.drawArrays(gl.LINES) method * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output */ function buildNativeLine(graphicsData, graphicsGeometry) { var i = 0; var shape = graphicsData.shape; var points = graphicsData.points || shape.points; var closedShape = shape.type !== math.SHAPES.POLY || shape.closeStroke; if (points.length === 0) { return; } var verts = graphicsGeometry.points; var indices = graphicsGeometry.indices; var length = points.length / 2; var startIndex = verts.length / 2; var currentIndex = startIndex; verts.push(points[0], points[1]); for (i = 1; i < length; i++) { verts.push(points[i * 2], points[(i * 2) + 1]); indices.push(currentIndex, currentIndex + 1); currentIndex++; } if (closedShape) { indices.push(currentIndex, startIndex); } } /** * Builds a complex polygon to draw * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.Graphics} graphicsData - The graphics object containing all the necessary properties * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape */ function buildComplexPoly(graphicsData, webGLData) { // TODO - no need to copy this as it gets turned into a Float32Array anyways.. var points = graphicsData.points.slice(); if (points.length < 6) { return; } // get first and last point.. figure out the middle! var indices = webGLData.indices; webGLData.points = points; webGLData.alpha = graphicsData.fillAlpha; webGLData.color = utils.hex2rgb(graphicsData.fillColor); // calculate the bounds.. var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; var x = 0; var y = 0; // get size.. for (var i = 0; i < points.length; i += 2) { x = points[i]; y = points[i + 1]; minX = x < minX ? x : minX; maxX = x > maxX ? x : maxX; minY = y < minY ? y : minY; maxY = y > maxY ? y : maxY; } // add a quad to the end cos there is no point making another buffer! points.push(minX, minY, maxX, minY, maxX, maxY, minX, maxY); // push a quad onto the end.. // TODO - this ain't needed! var length = points.length / 2; for (var i$1 = 0; i$1 < length; i$1++) { indices.push(i$1); } } /** * Calculate the points for a bezier curve and then draws it. * * Ignored from docs since it is not directly exposed. * * @ignore * @param {number} fromX - Starting point x * @param {number} fromY - Starting point y * @param {number} cpX - Control point x * @param {number} cpY - Control point y * @param {number} cpX2 - Second Control point x * @param {number} cpY2 - Second Control point y * @param {number} toX - Destination point x * @param {number} toY - Destination point y * @param {number} n - Number of segments approximating the bezier curve * @param {number[]} [path=[]] - Path array to push points into * @return {number[]} Array of points of the curve */ function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n, path) { if ( path === void 0 ) path = []; var dt = 0; var dt2 = 0; var dt3 = 0; var t2 = 0; var t3 = 0; path.push(fromX, fromY); for (var i = 1, j = 0; i <= n; ++i) { j = i / n; dt = (1 - j); dt2 = dt * dt; dt3 = dt2 * dt; t2 = j * j; t3 = t2 * j; path.push( (dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY) ); } return path; } /** * Draw a star shape with an arbitrary number of points. * * @class * @extends PIXI.Polygon * @memberof PIXI * @param {number} x - Center X position of the star * @param {number} y - Center Y position of the star * @param {number} points - The number of points of the star, must be > 1 * @param {number} radius - The outer radius of the star * @param {number} [innerRadius] - The inner radius between points, default half `radius` * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ var Star = /*@__PURE__*/(function (Polygon) { function Star(x, y, points, radius, innerRadius, rotation) { innerRadius = innerRadius || radius / 2; var startAngle = (-1 * Math.PI / 2) + rotation; var len = points * 2; var delta = math.PI_2 / len; var polygon = []; for (var i = 0; i < len; i++) { var r = i % 2 ? innerRadius : radius; var angle = (i * delta) + startAngle; polygon.push( x + (r * Math.cos(angle)), y + (r * Math.sin(angle)) ); } Polygon.call(this, polygon); } if ( Polygon ) Star.__proto__ = Polygon; Star.prototype = Object.create( Polygon && Polygon.prototype ); Star.prototype.constructor = Star; return Star; }(math.Polygon)); /** * Utilities for arc curves * @class * @private */ var ArcUtils = function ArcUtils () {}; ArcUtils.curveTo = function curveTo (x1, y1, x2, y2, radius, points) { var fromX = points[points.length - 2]; var fromY = points[points.length - 1]; var a1 = fromY - y1; var b1 = fromX - x1; var a2 = y2 - y1; var b2 = x2 - x1; var mm = Math.abs((a1 * b2) - (b1 * a2)); if (mm < 1.0e-8 || radius === 0) { if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { points.push(x1, y1); } return null; } var dd = (a1 * a1) + (b1 * b1); var cc = (a2 * a2) + (b2 * b2); var tt = (a1 * a2) + (b1 * b2); var k1 = radius * Math.sqrt(dd) / mm; var k2 = radius * Math.sqrt(cc) / mm; var j1 = k1 * tt / dd; var j2 = k2 * tt / cc; var cx = (k1 * b2) + (k2 * b1); var cy = (k1 * a2) + (k2 * a1); var px = b1 * (k2 + j1); var py = a1 * (k2 + j1); var qx = b2 * (k1 + j2); var qy = a2 * (k1 + j2); var startAngle = Math.atan2(py - cy, px - cx); var endAngle = Math.atan2(qy - cy, qx - cx); return { cx: (cx + x1), cy: (cy + y1), radius: radius, startAngle: startAngle, endAngle: endAngle, anticlockwise: (b1 * a2 > b2 * a1), }; }; /** * The arc method creates an arc/curve (used to create circles, or parts of circles). * * @private * @param {number} startX - Start x location of arc * @param {number} startY - Start y location of arc * @param {number} cx - The x-coordinate of the center of the circle * @param {number} cy - The y-coordinate of the center of the circle * @param {number} radius - The radius of the circle * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position * of the arc's circle) * @param {number} endAngle - The ending angle, in radians * @param {boolean} anticlockwise - Specifies whether the drawing should be * counter-clockwise or clockwise. False is default, and indicates clockwise, while true * indicates counter-clockwise. * @param {number} n - Number of segments * @param {number[]} points - Collection of points to add to */ ArcUtils.arc = function arc (startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points) { var sweep = endAngle - startAngle; var n = GRAPHICS_CURVES._segmentsCount( Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / math.PI_2) * 40 ); var theta = (sweep) / (n * 2); var theta2 = theta * 2; var cTheta = Math.cos(theta); var sTheta = Math.sin(theta); var segMinus = n - 1; var remainder = (segMinus % 1) / segMinus; for (var i = 0; i <= segMinus; ++i) { var real = i + (remainder * i); var angle = ((theta) + startAngle + (theta2 * real)); var c = Math.cos(angle); var s = -Math.sin(angle); points.push( (((cTheta * c) + (sTheta * s)) * radius) + cx, (((cTheta * -s) + (sTheta * c)) * radius) + cy ); } }; /** * Utilities for bezier curves * @class * @private */ var BezierUtils = function BezierUtils () {}; BezierUtils.curveLength = function curveLength (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { var n = 10; var result = 0.0; var t = 0.0; var t2 = 0.0; var t3 = 0.0; var nt = 0.0; var nt2 = 0.0; var nt3 = 0.0; var x = 0.0; var y = 0.0; var dx = 0.0; var dy = 0.0; var prevX = fromX; var prevY = fromY; for (var i = 1; i <= n; ++i) { t = i / n; t2 = t * t; t3 = t2 * t; nt = (1.0 - t); nt2 = nt * nt; nt3 = nt2 * nt; x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX); y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY); dx = prevX - x; dy = prevY - y; prevX = x; prevY = y; result += Math.sqrt((dx * dx) + (dy * dy)); } return result; }; /** * Calculate the points for a bezier curve and then draws it. * * Ignored from docs since it is not directly exposed. * * @ignore * @param {number} cpX - Control point x * @param {number} cpY - Control point y * @param {number} cpX2 - Second Control point x * @param {number} cpY2 - Second Control point y * @param {number} toX - Destination point x * @param {number} toY - Destination point y * @param {number[]} points - Path array to push points into */ BezierUtils.curveTo = function curveTo (cpX, cpY, cpX2, cpY2, toX, toY, points) { var fromX = points[points.length - 2]; var fromY = points[points.length - 1]; points.length -= 2; var n = GRAPHICS_CURVES._segmentsCount( BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) ); var dt = 0; var dt2 = 0; var dt3 = 0; var t2 = 0; var t3 = 0; points.push(fromX, fromY); for (var i = 1, j = 0; i <= n; ++i) { j = i / n; dt = (1 - j); dt2 = dt * dt; dt3 = dt2 * dt; t2 = j * j; t3 = t2 * j; points.push( (dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY) ); } }; /** * Utilities for quadratic curves * @class * @private */ var QuadraticUtils = function QuadraticUtils () {}; QuadraticUtils.curveLength = function curveLength (fromX, fromY, cpX, cpY, toX, toY) { var ax = fromX - (2.0 * cpX) + toX; var ay = fromY - (2.0 * cpY) + toY; var bx = (2.0 * cpX) - (2.0 * fromX); var by = (2.0 * cpY) - (2.0 * fromY); var a = 4.0 * ((ax * ax) + (ay * ay)); var b = 4.0 * ((ax * bx) + (ay * by)); var c = (bx * bx) + (by * by); var s = 2.0 * Math.sqrt(a + b + c); var a2 = Math.sqrt(a); var a32 = 2.0 * a * a2; var c2 = 2.0 * Math.sqrt(c); var ba = b / a2; return ( (a32 * s) + (a2 * b * (s - c2)) + ( ((4.0 * c * a) - (b * b)) * Math.log(((2.0 * a2) + ba + s) / (ba + c2)) ) ) / (4.0 * a32); }; /** * Calculate the points for a quadratic bezier curve and then draws it. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c * * @private * @param {number} cpX - Control point x * @param {number} cpY - Control point y * @param {number} toX - Destination point x * @param {number} toY - Destination point y * @param {number[]} points - Points to add segments to. */ QuadraticUtils.curveTo = function curveTo (cpX, cpY, toX, toY, points) { var fromX = points[points.length - 2]; var fromY = points[points.length - 1]; var n = GRAPHICS_CURVES._segmentsCount( QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY) ); var xa = 0; var ya = 0; for (var i = 1; i <= n; ++i) { var j = i / n; xa = fromX + ((cpX - fromX) * j); ya = fromY + ((cpY - fromY) * j); points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), ya + (((cpY + ((toY - cpY) * j)) - ya) * j)); } }; /** * A structure to hold interim batch objects for Graphics. * @class * @memberof PIXI.graphicsUtils */ var BatchPart = function BatchPart() { this.reset(); }; /** * Begin batch part * * @param {PIXI.FillStyle | PIXI.LineStyle} style * @param {number} startIndex * @param {number} attribStart */ BatchPart.prototype.begin = function begin (style, startIndex, attribStart) { this.reset(); this.style = style; this.start = startIndex; this.attribStart = attribStart; }; /** * End batch part * * @param {number} endIndex * @param {number} endAttrib */ BatchPart.prototype.end = function end (endIndex, endAttrib) { this.attribSize = endAttrib - this.attribStart; this.size = endIndex - this.start; }; BatchPart.prototype.reset = function reset () { this.style = null; this.size = 0; this.start = 0; this.attribStart = 0; this.attribSize = 0; }; /** * Generalized convenience utilities for Graphics. * * @namespace PIXI.graphicsUtils */ /** * Map of fill commands for each shape type. * * @memberof PIXI.graphicsUtils * @member {Object} */ var FILL_COMMANDS = {}; FILL_COMMANDS[math.SHAPES.POLY] = buildPoly; FILL_COMMANDS[math.SHAPES.CIRC] = buildCircle; FILL_COMMANDS[math.SHAPES.ELIP] = buildCircle; FILL_COMMANDS[math.SHAPES.RECT] = buildRectangle; FILL_COMMANDS[math.SHAPES.RREC] = buildRoundedRectangle; /** * Batch pool, stores unused batches for preventing allocations. * * @memberof PIXI.graphicsUtils * @type {Array} */ var BATCH_POOL = []; /** * Draw call pool, stores unused draw calls for preventing allocations. * * @memberof PIXI.graphicsUtils * @type {Array} */ var DRAW_CALL_POOL = []; var index = ({ buildPoly: buildPoly, buildCircle: buildCircle, buildRectangle: buildRectangle, buildRoundedRectangle: buildRoundedRectangle, FILL_COMMANDS: FILL_COMMANDS, BATCH_POOL: BATCH_POOL, DRAW_CALL_POOL: DRAW_CALL_POOL, buildLine: buildLine, buildComplexPoly: buildComplexPoly, bezierCurveTo: bezierCurveTo, Star: Star, ArcUtils: ArcUtils, BezierUtils: BezierUtils, QuadraticUtils: QuadraticUtils, BatchPart: BatchPart }); /** * A class to contain data useful for Graphics objects * * @class * @memberof PIXI */ var GraphicsData = function GraphicsData(shape, fillStyle, lineStyle, matrix) { if ( fillStyle === void 0 ) fillStyle = null; if ( lineStyle === void 0 ) lineStyle = null; if ( matrix === void 0 ) matrix = null; /** * The shape object to draw. * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} */ this.shape = shape; /** * The style of the line. * @member {PIXI.LineStyle} */ this.lineStyle = lineStyle; /** * The style of the fill. * @member {PIXI.FillStyle} */ this.fillStyle = fillStyle; /** * The transform matrix. * @member {PIXI.Matrix} */ this.matrix = matrix; /** * The type of the shape, see the Const.Shapes file for all the existing types, * @member {number} */ this.type = shape.type; /** * The collection of points. * @member {number[]} */ this.points = []; /** * The collection of holes. * @member {PIXI.GraphicsData[]} */ this.holes = []; }; /** * Creates a new GraphicsData object with the same values as this one. * * @return {PIXI.GraphicsData} Cloned GraphicsData object */ GraphicsData.prototype.clone = function clone () { return new GraphicsData( this.shape, this.fillStyle, this.lineStyle, this.matrix ); }; /** * Destroys the Graphics data. */ GraphicsData.prototype.destroy = function destroy () { this.shape = null; this.holes.length = 0; this.holes = null; this.points.length = 0; this.points = null; this.lineStyle = null; this.fillStyle = null; }; var tmpPoint = new math.Point(); var tmpBounds = new display.Bounds(); /** * The Graphics class contains methods used to draw primitive shapes such as lines, circles and * rectangles to the display, and to color and fill them. * * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster. * * @class * @extends PIXI.BatchGeometry * @memberof PIXI */ var GraphicsGeometry = /*@__PURE__*/(function (BatchGeometry) { function GraphicsGeometry() { BatchGeometry.call(this); /** * An array of points to draw, 2 numbers per point * * @member {number[]} * @protected */ this.points = []; /** * The collection of colors * * @member {number[]} * @protected */ this.colors = []; /** * The UVs collection * * @member {number[]} * @protected */ this.uvs = []; /** * The indices of the vertices * * @member {number[]} * @protected */ this.indices = []; /** * Reference to the texture IDs. * * @member {number[]} * @protected */ this.textureIds = []; /** * The collection of drawn shapes. * * @member {PIXI.GraphicsData[]} * @protected */ this.graphicsData = []; /** * Used to detect if the graphics object has changed. * * @member {number} * @protected */ this.dirty = 0; /** * Batches need to regenerated if the geometry is updated. * * @member {number} * @protected */ this.batchDirty = -1; /** * Used to check if the cache is dirty. * * @member {number} * @protected */ this.cacheDirty = -1; /** * Used to detect if we cleared the graphicsData. * * @member {number} * @default 0 * @protected */ this.clearDirty = 0; /** * List of current draw calls drived from the batches. * * @member {object[]} * @protected */ this.drawCalls = []; /** * Intermediate abstract format sent to batch system. * Can be converted to drawCalls or to batchable objects. * * @member {PIXI.graphicsUtils.BatchPart[]} * @protected */ this.batches = []; /** * Index of the last batched shape in the stack of calls. * * @member {number} * @protected */ this.shapeIndex = 0; /** * Cached bounds. * * @member {PIXI.Bounds} * @protected */ this._bounds = new display.Bounds(); /** * The bounds dirty flag. * * @member {number} * @protected */ this.boundsDirty = -1; /** * Padding to add to the bounds. * * @member {number} * @default 0 */ this.boundsPadding = 0; this.batchable = false; this.indicesUint16 = null; this.uvsFloat32 = null; /** * Minimal distance between points that are considered different. * Affects line tesselation. * * @member {number} */ this.closePointEps = 1e-4; } if ( BatchGeometry ) GraphicsGeometry.__proto__ = BatchGeometry; GraphicsGeometry.prototype = Object.create( BatchGeometry && BatchGeometry.prototype ); GraphicsGeometry.prototype.constructor = GraphicsGeometry; var prototypeAccessors = { bounds: { configurable: true } }; /** * Get the current bounds of the graphic geometry. * * @member {PIXI.Bounds} * @readonly */ prototypeAccessors.bounds.get = function () { if (this.boundsDirty !== this.dirty) { this.boundsDirty = this.dirty; this.calculateBounds(); } return this._bounds; }; /** * Call if you changed graphicsData manually. * Empties all batch buffers. */ GraphicsGeometry.prototype.invalidate = function invalidate () { this.boundsDirty = -1; this.dirty++; this.batchDirty++; this.shapeIndex = 0; this.points.length = 0; this.colors.length = 0; this.uvs.length = 0; this.indices.length = 0; this.textureIds.length = 0; for (var i = 0; i < this.drawCalls.length; i++) { this.drawCalls[i].textures.length = 0; DRAW_CALL_POOL.push(this.drawCalls[i]); } this.drawCalls.length = 0; for (var i$1 = 0; i$1 < this.batches.length; i$1++) { var batchPart = this.batches[i$1]; batchPart.reset(); BATCH_POOL.push(batchPart); } this.batches.length = 0; }; /** * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. * * @return {PIXI.GraphicsGeometry} This GraphicsGeometry object. Good for chaining method calls */ GraphicsGeometry.prototype.clear = function clear () { if (this.graphicsData.length > 0) { this.invalidate(); this.clearDirty++; this.graphicsData.length = 0; } return this; }; /** * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. * * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. * @param {PIXI.FillStyle} fillStyle - Defines style of the fill. * @param {PIXI.LineStyle} lineStyle - Defines style of the lines. * @param {PIXI.Matrix} matrix - Transform applied to the points of the shape. * @return {PIXI.GraphicsGeometry} Returns geometry for chaining. */ GraphicsGeometry.prototype.drawShape = function drawShape (shape, fillStyle, lineStyle, matrix) { var data = new GraphicsData(shape, fillStyle, lineStyle, matrix); this.graphicsData.push(data); this.dirty++; return this; }; /** * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. * * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. * @param {PIXI.Matrix} matrix - Transform applied to the points of the shape. * @return {PIXI.GraphicsGeometry} Returns geometry for chaining. */ GraphicsGeometry.prototype.drawHole = function drawHole (shape, matrix) { if (!this.graphicsData.length) { return null; } var data = new GraphicsData(shape, null, null, matrix); var lastShape = this.graphicsData[this.graphicsData.length - 1]; data.lineStyle = lastShape.lineStyle; lastShape.holes.push(data); this.dirty++; return this; }; /** * Destroys the Graphics object. * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all * options have been set to that value * @param {boolean} [options.children=false] - if set to true, all the children will have * their destroy method called as well. 'options' will be passed on to those calls. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true * Should it destroy the texture of the child sprite * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true * Should it destroy the base texture of the child sprite */ GraphicsGeometry.prototype.destroy = function destroy (options) { BatchGeometry.prototype.destroy.call(this, options); // destroy each of the GraphicsData objects for (var i = 0; i < this.graphicsData.length; ++i) { this.graphicsData[i].destroy(); } this.points.length = 0; this.points = null; this.colors.length = 0; this.colors = null; this.uvs.length = 0; this.uvs = null; this.indices.length = 0; this.indices = null; this.indexBuffer.destroy(); this.indexBuffer = null; this.graphicsData.length = 0; this.graphicsData = null; this.drawCalls.length = 0; this.drawCalls = null; this.batches.length = 0; this.batches = null; this._bounds = null; }; /** * Check to see if a point is contained within this geometry. * * @param {PIXI.Point} point - Point to check if it's contained. * @return {Boolean} `true` if the point is contained within geometry. */ GraphicsGeometry.prototype.containsPoint = function containsPoint (point) { var graphicsData = this.graphicsData; for (var i = 0; i < graphicsData.length; ++i) { var data = graphicsData[i]; if (!data.fillStyle.visible) { continue; } // only deal with fills.. if (data.shape) { if (data.matrix) { data.matrix.applyInverse(point, tmpPoint); } else { tmpPoint.copyFrom(point); } if (data.shape.contains(tmpPoint.x, tmpPoint.y)) { var hitHole = false; if (data.holes) { for (var i$1 = 0; i$1 < data.holes.length; i$1++) { var hole = data.holes[i$1]; if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) { hitHole = true; break; } } } if (!hitHole) { return true; } } } } return false; }; /** * Generates intermediate batch data. Either gets converted to drawCalls * or used to convert to batch objects directly by the Graphics object. */ GraphicsGeometry.prototype.updateBatches = function updateBatches () { if (!this.graphicsData.length) { this.batchable = true; return; } if (!this.validateBatching()) { return; } this.cacheDirty = this.dirty; var uvs = this.uvs; var graphicsData = this.graphicsData; var batchPart = null; var currentStyle = null; if (this.batches.length > 0) { batchPart = this.batches[this.batches.length - 1]; currentStyle = batchPart.style; } for (var i = this.shapeIndex; i < graphicsData.length; i++) { this.shapeIndex++; var data = graphicsData[i]; var fillStyle = data.fillStyle; var lineStyle = data.lineStyle; var command = FILL_COMMANDS[data.type]; // build out the shapes points.. command.build(data); if (data.matrix) { this.transformPoints(data.points, data.matrix); } for (var j = 0; j < 2; j++) { var style = (j === 0) ? fillStyle : lineStyle; if (!style.visible) { continue; } var nextTexture = style.texture.baseTexture; var index = this.indices.length; var attribIndex = this.points.length / 2; nextTexture.wrapMode = constants.WRAP_MODES.REPEAT; if (j === 0) { this.processFill(data); } else { this.processLine(data); } var size = (this.points.length / 2) - attribIndex; if (size === 0) { continue; } // close batch if style is different if (batchPart && !this._compareStyles(currentStyle, style)) { batchPart.end(index, attribIndex); batchPart = null; } // spawn new batch if its first batch or previous was closed if (!batchPart) { batchPart = BATCH_POOL.pop() || new BatchPart(); batchPart.begin(style, index, attribIndex); this.batches.push(batchPart); currentStyle = style; } this.addUvs(this.points, uvs, style.texture, attribIndex, size, style.matrix); } } if (batchPart) { var index$1 = this.indices.length; var attrib = this.points.length / 2; batchPart.end(index$1, attrib); } if (this.batches.length === 0) { // there are no visible styles in GraphicsData // its possible that someone wants Graphics just for the bounds this.batchable = true; return; } this.indicesUint16 = new Uint16Array(this.indices); // TODO make this a const.. this.batchable = this.isBatchable(); if (this.batchable) { this.packBatches(); } else { this.buildDrawCalls(); } }; /** * Affinity check * * @param {PIXI.FillStyle | PIXI.LineStyle} styleA * @param {PIXI.FillStyle | PIXI.LineStyle} styleB */ GraphicsGeometry.prototype._compareStyles = function _compareStyles (styleA, styleB) { if (!styleA || !styleB) { return false; } if (styleA.texture.baseTexture !== styleB.texture.baseTexture) { return false; } if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) { return false; } if (!!styleA.native !== !!styleB.native) { return false; } return true; }; /** * Test geometry for batching process. * * @protected */ GraphicsGeometry.prototype.validateBatching = function validateBatching () { if (this.dirty === this.cacheDirty || !this.graphicsData.length) { return false; } for (var i = 0, l = this.graphicsData.length; i < l; i++) { var data = this.graphicsData[i]; var fill = data.fillStyle; var line = data.lineStyle; if (fill && !fill.texture.baseTexture.valid) { return false; } if (line && !line.texture.baseTexture.valid) { return false; } } return true; }; /** * Offset the indices so that it works with the batcher. * * @protected */ GraphicsGeometry.prototype.packBatches = function packBatches () { this.batchDirty++; this.uvsFloat32 = new Float32Array(this.uvs); var batches = this.batches; for (var i = 0, l = batches.length; i < l; i++) { var batch = batches[i]; for (var j = 0; j < batch.size; j++) { var index = batch.start + j; this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart; } } }; /** * Checks to see if this graphics geometry can be batched. * Currently it needs to be small enough and not contain any native lines. * * @protected */ GraphicsGeometry.prototype.isBatchable = function isBatchable () { var batches = this.batches; for (var i = 0; i < batches.length; i++) { if (batches[i].style.native) { return false; } } return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2); }; /** * Converts intermediate batches data to drawCalls. * * @protected */ GraphicsGeometry.prototype.buildDrawCalls = function buildDrawCalls () { var TICK = ++core.BaseTexture._globalBatch; for (var i = 0; i < this.drawCalls.length; i++) { this.drawCalls[i].textures.length = 0; DRAW_CALL_POOL.push(this.drawCalls[i]); } this.drawCalls.length = 0; var colors = this.colors; var textureIds = this.textureIds; var currentGroup = DRAW_CALL_POOL.pop(); if (!currentGroup) { currentGroup = new core.BatchDrawCall(); currentGroup.textures = new core.BatchTextureArray(); } currentGroup.textures.count = 0; currentGroup.start = 0; currentGroup.size = 0; currentGroup.type = constants.DRAW_MODES.TRIANGLES; var textureCount = 0; var currentTexture = null; var textureId = 0; var native = false; var drawMode = constants.DRAW_MODES.TRIANGLES; var index = 0; this.drawCalls.push(currentGroup); // TODO - this can be simplified for (var i$1 = 0; i$1 < this.batches.length; i$1++) { var data = this.batches[i$1]; // TODO add some full on MAX_TEXTURE CODE.. var MAX_TEXTURES = 8; var style = data.style; var nextTexture = style.texture.baseTexture; if (native !== !!style.native) { native = !!style.native; drawMode = native ? constants.DRAW_MODES.LINES : constants.DRAW_MODES.TRIANGLES; // force the batch to break! currentTexture = null; textureCount = MAX_TEXTURES; TICK++; } if (currentTexture !== nextTexture) { currentTexture = nextTexture; if (nextTexture._batchEnabled !== TICK) { if (textureCount === MAX_TEXTURES) { TICK++; textureCount = 0; if (currentGroup.size > 0) { currentGroup = DRAW_CALL_POOL.pop(); if (!currentGroup) { currentGroup = new core.BatchDrawCall(); currentGroup.textures = new core.BatchTextureArray(); } this.drawCalls.push(currentGroup); } currentGroup.start = index; currentGroup.size = 0; currentGroup.textures.count = 0; currentGroup.type = drawMode; } // TODO add this to the render part.. nextTexture.touched = 1;// touch; nextTexture._batchEnabled = TICK; nextTexture._batchLocation = textureCount; nextTexture.wrapMode = 10497; currentGroup.textures.elements[currentGroup.textures.count++] = nextTexture; textureCount++; } } currentGroup.size += data.size; index += data.size; textureId = nextTexture._batchLocation; this.addColors(colors, style.color, style.alpha, data.attribSize); this.addTextureIds(textureIds, textureId, data.attribSize); } core.BaseTexture._globalBatch = TICK; // upload.. // merge for now! this.packAttributes(); }; /** * Packs attributes to single buffer. * * @protected */ GraphicsGeometry.prototype.packAttributes = function packAttributes () { var verts = this.points; var uvs = this.uvs; var colors = this.colors; var textureIds = this.textureIds; // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes var glPoints = new ArrayBuffer(verts.length * 3 * 4); var f32 = new Float32Array(glPoints); var u32 = new Uint32Array(glPoints); var p = 0; for (var i = 0; i < verts.length / 2; i++) { f32[p++] = verts[i * 2]; f32[p++] = verts[(i * 2) + 1]; f32[p++] = uvs[i * 2]; f32[p++] = uvs[(i * 2) + 1]; u32[p++] = colors[i]; f32[p++] = textureIds[i]; } this._buffer.update(glPoints); this._indexBuffer.update(this.indicesUint16); }; /** * Process fill part of Graphics. * * @param {PIXI.GraphicsData} data * @protected */ GraphicsGeometry.prototype.processFill = function processFill (data) { if (data.holes.length) { this.processHoles(data.holes); buildPoly.triangulate(data, this); } else { var command = FILL_COMMANDS[data.type]; command.triangulate(data, this); } }; /** * Process line part of Graphics. * * @param {PIXI.GraphicsData} data * @protected */ GraphicsGeometry.prototype.processLine = function processLine (data) { buildLine(data, this); for (var i = 0; i < data.holes.length; i++) { buildLine(data.holes[i], this); } }; /** * Process the holes data. * * @param {PIXI.GraphicsData[]} holes - Holes to render * @protected */ GraphicsGeometry.prototype.processHoles = function processHoles (holes) { for (var i = 0; i < holes.length; i++) { var hole = holes[i]; var command = FILL_COMMANDS[hole.type]; command.build(hole); if (hole.matrix) { this.transformPoints(hole.points, hole.matrix); } } }; /** * Update the local bounds of the object. Expensive to use performance-wise. * * @protected */ GraphicsGeometry.prototype.calculateBounds = function calculateBounds () { var bounds = this._bounds; var sequenceBounds = tmpBounds; var curMatrix = math.Matrix.IDENTITY; this._bounds.clear(); sequenceBounds.clear(); for (var i = 0; i < this.graphicsData.length; i++) { var data = this.graphicsData[i]; var shape = data.shape; var type = data.type; var lineStyle = data.lineStyle; var nextMatrix = data.matrix || math.Matrix.IDENTITY; var lineWidth = 0.0; if (lineStyle && lineStyle.visible) { var alignment = lineStyle.alignment; lineWidth = lineStyle.width; if (type === math.SHAPES.POLY) { lineWidth = lineWidth * (0.5 + Math.abs(0.5 - alignment)); } else { lineWidth = lineWidth * Math.max(0, alignment); } } if (curMatrix !== nextMatrix) { if (!sequenceBounds.isEmpty()) { bounds.addBoundsMatrix(sequenceBounds, curMatrix); sequenceBounds.clear(); } curMatrix = nextMatrix; } if (type === math.SHAPES.RECT || type === math.SHAPES.RREC) { sequenceBounds.addFramePad(shape.x, shape.y, shape.x + shape.width, shape.y + shape.height, lineWidth, lineWidth); } else if (type === math.SHAPES.CIRC) { sequenceBounds.addFramePad(shape.x, shape.y, shape.x, shape.y, shape.radius + lineWidth, shape.radius + lineWidth); } else if (type === math.SHAPES.ELIP) { sequenceBounds.addFramePad(shape.x, shape.y, shape.x, shape.y, shape.width + lineWidth, shape.height + lineWidth); } else { // adding directly to the bounds bounds.addVerticesMatrix(curMatrix, shape.points, 0, shape.points.length, lineWidth, lineWidth); } } if (!sequenceBounds.isEmpty()) { bounds.addBoundsMatrix(sequenceBounds, curMatrix); } bounds.pad(this.boundsPadding, this.boundsPadding); }; /** * Transform points using matrix. * * @protected * @param {number[]} points - Points to transform * @param {PIXI.Matrix} matrix - Transform matrix */ GraphicsGeometry.prototype.transformPoints = function transformPoints (points, matrix) { for (var i = 0; i < points.length / 2; i++) { var x = points[(i * 2)]; var y = points[(i * 2) + 1]; points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx; points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty; } }; /** * Add colors. * * @protected * @param {number[]} colors - List of colors to add to * @param {number} color - Color to add * @param {number} alpha - Alpha to use * @param {number} size - Number of colors to add */ GraphicsGeometry.prototype.addColors = function addColors (colors, color, alpha, size) { // TODO use the premultiply bits Ivan added var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16); var rgba = utils.premultiplyTint(rgb, alpha); while (size-- > 0) { colors.push(rgba); } }; /** * Add texture id that the shader/fragment wants to use. * * @protected * @param {number[]} textureIds * @param {number} id * @param {number} size */ GraphicsGeometry.prototype.addTextureIds = function addTextureIds (textureIds, id, size) { while (size-- > 0) { textureIds.push(id); } }; /** * Generates the UVs for a shape. * * @protected * @param {number[]} verts - Vertices * @param {number[]} uvs - UVs * @param {PIXI.Texture} texture - Reference to Texture * @param {number} start - Index buffer start index. * @param {number} size - The size/length for index buffer. * @param {PIXI.Matrix} [matrix] - Optional transform for all points. */ GraphicsGeometry.prototype.addUvs = function addUvs (verts, uvs, texture, start, size, matrix) { var index = 0; var uvsStart = uvs.length; var frame = texture.frame; while (index < size) { var x = verts[(start + index) * 2]; var y = verts[((start + index) * 2) + 1]; if (matrix) { var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx; y = (matrix.b * x) + (matrix.d * y) + matrix.ty; x = nx; } index++; uvs.push(x / frame.width, y / frame.height); } var baseTexture = texture.baseTexture; if (frame.width < baseTexture.width || frame.height < baseTexture.height) { this.adjustUvs(uvs, texture, uvsStart, size); } }; /** * Modify uvs array according to position of texture region * Does not work with rotated or trimmed textures * * @param {number[]} uvs array * @param {PIXI.Texture} texture region * @param {number} start starting index for uvs * @param {number} size how many points to adjust */ GraphicsGeometry.prototype.adjustUvs = function adjustUvs (uvs, texture, start, size) { var baseTexture = texture.baseTexture; var eps = 1e-6; var finish = start + (size * 2); var frame = texture.frame; var scaleX = frame.width / baseTexture.width; var scaleY = frame.height / baseTexture.height; var offsetX = frame.x / frame.width; var offsetY = frame.y / frame.height; var minX = Math.floor(uvs[start] + eps); var minY = Math.floor(uvs[start + 1] + eps); for (var i = start + 2; i < finish; i += 2) { minX = Math.min(minX, Math.floor(uvs[i] + eps)); minY = Math.min(minY, Math.floor(uvs[i + 1] + eps)); } offsetX -= minX; offsetY -= minY; for (var i$1 = start; i$1 < finish; i$1 += 2) { uvs[i$1] = (uvs[i$1] + offsetX) * scaleX; uvs[i$1 + 1] = (uvs[i$1 + 1] + offsetY) * scaleY; } }; Object.defineProperties( GraphicsGeometry.prototype, prototypeAccessors ); return GraphicsGeometry; }(core.BatchGeometry)); /** * The maximum number of points to consider an object "batchable", * able to be batched by the renderer's batch system. * * @memberof PIXI.GraphicsGeometry * @static * @member {number} BATCHABLE_SIZE * @default 100 */ GraphicsGeometry.BATCHABLE_SIZE = 100; /** * Represents the line style for Graphics. * @memberof PIXI * @class * @extends PIXI.FillStyle */ var LineStyle = /*@__PURE__*/(function (FillStyle) { function LineStyle () { FillStyle.apply(this, arguments); } if ( FillStyle ) LineStyle.__proto__ = FillStyle; LineStyle.prototype = Object.create( FillStyle && FillStyle.prototype ); LineStyle.prototype.constructor = LineStyle; LineStyle.prototype.clone = function clone () { var obj = new LineStyle(); obj.color = this.color; obj.alpha = this.alpha; obj.texture = this.texture; obj.matrix = this.matrix; obj.visible = this.visible; obj.width = this.width; obj.alignment = this.alignment; obj.native = this.native; return obj; }; /** * Reset the line style to default. */ LineStyle.prototype.reset = function reset () { FillStyle.prototype.reset.call(this); // Override default line style color this.color = 0x0; /** * The width (thickness) of any lines drawn. * * @member {number} * @default 0 */ this.width = 0; /** * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). * * @member {number} * @default 0 */ this.alignment = 0.5; /** * If true the lines will be draw using LINES instead of TRIANGLE_STRIP * * @member {boolean} * @default false */ this.native = false; }; return LineStyle; }(FillStyle)); var temp = new Float32Array(3); // a default shaders map used by graphics.. var DEFAULT_SHADERS = {}; /** * The Graphics class contains methods used to draw primitive shapes such as lines, circles and * rectangles to the display, and to color and fill them. * * Note that because Graphics can share a GraphicsGeometry with other instances, * it is necessary to call `destroy()` to properly dereference the underlying * GraphicsGeometry and avoid a memory leak. Alternatively, keep using the same * Graphics instance and call `clear()` between redraws. * * @class * @extends PIXI.Container * @memberof PIXI */ var Graphics = /*@__PURE__*/(function (Container) { function Graphics(geometry) { if ( geometry === void 0 ) geometry = null; Container.call(this); /** * Includes vertex positions, face indices, normals, colors, UVs, and * custom attributes within buffers, reducing the cost of passing all * this data to the GPU. Can be shared between multiple Mesh or Graphics objects. * @member {PIXI.GraphicsGeometry} * @readonly */ this.geometry = geometry || new GraphicsGeometry(); this.geometry.refCount++; /** * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. * Can be shared between multiple Graphics objects. * @member {PIXI.Shader} */ this.shader = null; /** * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g., * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. * @member {PIXI.State} */ this.state = core.State.for2d(); /** * Current fill style * * @member {PIXI.FillStyle} * @protected */ this._fillStyle = new FillStyle(); /** * Current line style * * @member {PIXI.LineStyle} * @protected */ this._lineStyle = new LineStyle(); /** * Current shape transform matrix. * * @member {PIXI.Matrix} * @protected */ this._matrix = null; /** * Current hole mode is enabled. * * @member {boolean} * @default false * @protected */ this._holeMode = false; /** * Current path * * @member {PIXI.Polygon} * @protected */ this.currentPath = null; /** * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. * This is useful if your graphics element does not change often, as it will speed up the rendering * of the object in exchange for taking up texture memory. It is also useful if you need the graphics * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if * you are constantly redrawing the graphics element. * * @name cacheAsBitmap * @member {boolean} * @memberof PIXI.Graphics# * @default false */ /** * A collections of batches! These can be drawn by the renderer batch system. * * @protected * @member {object[]} */ this.batches = []; /** * Update dirty for limiting calculating tints for batches. * * @protected * @member {number} * @default -1 */ this.batchTint = -1; /** * Copy of the object vertex data. * * @protected * @member {Float32Array} */ this.vertexData = null; this._transformID = -1; this.batchDirty = -1; /** * Renderer plugin for batching * * @member {string} * @default 'batch' */ this.pluginName = 'batch'; // Set default this.tint = 0xFFFFFF; this.blendMode = constants.BLEND_MODES.NORMAL; } if ( Container ) Graphics.__proto__ = Container; Graphics.prototype = Object.create( Container && Container.prototype ); Graphics.prototype.constructor = Graphics; var prototypeAccessors = { blendMode: { configurable: true },tint: { configurable: true },fill: { configurable: true },line: { configurable: true } }; /** * Creates a new Graphics object with the same values as this one. * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) * * @return {PIXI.Graphics} A clone of the graphics object */ Graphics.prototype.clone = function clone () { this.finishPoly(); return new Graphics(this.geometry); }; /** * The blend mode to be applied to the graphic shape. Apply a value of * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. * * @member {number} * @default PIXI.BLEND_MODES.NORMAL; * @see PIXI.BLEND_MODES */ prototypeAccessors.blendMode.set = function (value) { this.state.blendMode = value; }; prototypeAccessors.blendMode.get = function () { return this.state.blendMode; }; /** * The tint applied to the graphic shape. This is a hex value. A value of * 0xFFFFFF will remove any tint effect. * * @member {number} * @default 0xFFFFFF */ prototypeAccessors.tint.get = function () { return this._tint; }; prototypeAccessors.tint.set = function (value) { this._tint = value; }; /** * The current fill style. * * @member {PIXI.FillStyle} * @readonly */ prototypeAccessors.fill.get = function () { return this._fillStyle; }; /** * The current line style. * * @member {PIXI.LineStyle} * @readonly */ prototypeAccessors.line.get = function () { return this._lineStyle; }; /** * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() * method or the drawCircle() method. * * @method PIXI.Graphics#lineStyle * @param {number} [width=0] - width of the line to draw, will update the objects stored style * @param {number} [color=0x0] - color of the line to draw, will update the objects stored style * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style * @param {number} [alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) * @param {boolean} [native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ /** * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() * method or the drawCircle() method. * * @param {object} [options] - Line style options * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.lineStyle = function lineStyle (options) { // Support non-object params: (width, color, alpha, alignment, native) if (typeof options === 'number') { var args = arguments; options = { width: args[0] || 0, color: args[1] || 0x0, alpha: args[2] !== undefined ? args[2] : 1, alignment: args[3] !== undefined ? args[3] : 0.5, native: !!args[4], }; } return this.lineTextureStyle(options); }; /** * Like line style but support texture for line fill. * * @param {object} [options] - Collection of options for setting line style. * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to use * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style. * Default 0xFFFFFF if texture present. * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style * @param {PIXI.Matrix} [options.matrix=null] Texture matrix to transform texture * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.lineTextureStyle = function lineTextureStyle (options) { // backward compatibility with params: (width, texture, // color, alpha, matrix, alignment, native) if (typeof options === 'number') { utils.deprecation('v5.2.0', 'Please use object-based options for Graphics#lineTextureStyle'); var width = arguments[0]; var texture = arguments[1]; var color = arguments[2]; var alpha = arguments[3]; var matrix = arguments[4]; var alignment = arguments[5]; var native = arguments[6]; options = { width: width, texture: texture, color: color, alpha: alpha, matrix: matrix, alignment: alignment, native: native }; // Remove undefined keys Object.keys(options).forEach(function (key) { return options[key] === undefined && delete options[key]; }); } // Apply defaults options = Object.assign({ width: 0, texture: core.Texture.WHITE, color: (options && options.texture) ? 0xFFFFFF : 0x0, alpha: 1, matrix: null, alignment: 0.5, native: false, }, options); if (this.currentPath) { this.startPoly(); } var visible = options.width > 0 && options.alpha > 0; if (!visible) { this._lineStyle.reset(); } else { if (options.matrix) { options.matrix = options.matrix.clone(); options.matrix.invert(); } Object.assign(this._lineStyle, { visible: visible }, options); } return this; }; /** * Start a polygon object internally * @protected */ Graphics.prototype.startPoly = function startPoly () { if (this.currentPath) { var points = this.currentPath.points; var len = this.currentPath.points.length; if (len > 2) { this.drawShape(this.currentPath); this.currentPath = new math.Polygon(); this.currentPath.closeStroke = false; this.currentPath.points.push(points[len - 2], points[len - 1]); } } else { this.currentPath = new math.Polygon(); this.currentPath.closeStroke = false; } }; /** * Finish the polygon object. * @protected */ Graphics.prototype.finishPoly = function finishPoly () { if (this.currentPath) { if (this.currentPath.points.length > 2) { this.drawShape(this.currentPath); this.currentPath = null; } else { this.currentPath.points.length = 0; } } }; /** * Moves the current drawing position to x, y. * * @param {number} x - the X coordinate to move to * @param {number} y - the Y coordinate to move to * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.moveTo = function moveTo (x, y) { this.startPoly(); this.currentPath.points[0] = x; this.currentPath.points[1] = y; return this; }; /** * Draws a line using the current line style from the current drawing position to (x, y); * The current drawing position is then set to (x, y). * * @param {number} x - the X coordinate to draw to * @param {number} y - the Y coordinate to draw to * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.lineTo = function lineTo (x, y) { if (!this.currentPath) { this.moveTo(0, 0); } // remove duplicates.. var points = this.currentPath.points; var fromX = points[points.length - 2]; var fromY = points[points.length - 1]; if (fromX !== x || fromY !== y) { points.push(x, y); } return this; }; /** * Initialize the curve * * @protected * @param {number} [x=0] * @param {number} [y=0] */ Graphics.prototype._initCurve = function _initCurve (x, y) { if ( x === void 0 ) x = 0; if ( y === void 0 ) y = 0; if (this.currentPath) { if (this.currentPath.points.length === 0) { this.currentPath.points = [x, y]; } } else { this.moveTo(x, y); } }; /** * Calculate the points for a quadratic bezier curve and then draws it. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c * * @param {number} cpX - Control point x * @param {number} cpY - Control point y * @param {number} toX - Destination point x * @param {number} toY - Destination point y * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.quadraticCurveTo = function quadraticCurveTo (cpX, cpY, toX, toY) { this._initCurve(); var points = this.currentPath.points; if (points.length === 0) { this.moveTo(0, 0); } QuadraticUtils.curveTo(cpX, cpY, toX, toY, points); return this; }; /** * Calculate the points for a bezier curve and then draws it. * * @param {number} cpX - Control point x * @param {number} cpY - Control point y * @param {number} cpX2 - Second Control point x * @param {number} cpY2 - Second Control point y * @param {number} toX - Destination point x * @param {number} toY - Destination point y * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.bezierCurveTo = function bezierCurveTo (cpX, cpY, cpX2, cpY2, toX, toY) { this._initCurve(); BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points); return this; }; /** * The arcTo() method creates an arc/curve between two tangents on the canvas. * * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! * * @param {number} x1 - The x-coordinate of the first tangent point of the arc * @param {number} y1 - The y-coordinate of the first tangent point of the arc * @param {number} x2 - The x-coordinate of the end of the arc * @param {number} y2 - The y-coordinate of the end of the arc * @param {number} radius - The radius of the arc * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.arcTo = function arcTo (x1, y1, x2, y2, radius) { this._initCurve(x1, y1); var points = this.currentPath.points; var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points); if (result) { var cx = result.cx; var cy = result.cy; var radius$1 = result.radius; var startAngle = result.startAngle; var endAngle = result.endAngle; var anticlockwise = result.anticlockwise; this.arc(cx, cy, radius$1, startAngle, endAngle, anticlockwise); } return this; }; /** * The arc method creates an arc/curve (used to create circles, or parts of circles). * * @param {number} cx - The x-coordinate of the center of the circle * @param {number} cy - The y-coordinate of the center of the circle * @param {number} radius - The radius of the circle * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position * of the arc's circle) * @param {number} endAngle - The ending angle, in radians * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be * counter-clockwise or clockwise. False is default, and indicates clockwise, while true * indicates counter-clockwise. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.arc = function arc (cx, cy, radius, startAngle, endAngle, anticlockwise) { if ( anticlockwise === void 0 ) anticlockwise = false; if (startAngle === endAngle) { return this; } if (!anticlockwise && endAngle <= startAngle) { endAngle += math.PI_2; } else if (anticlockwise && startAngle <= endAngle) { startAngle += math.PI_2; } var sweep = endAngle - startAngle; if (sweep === 0) { return this; } var startX = cx + (Math.cos(startAngle) * radius); var startY = cy + (Math.sin(startAngle) * radius); var eps = this.geometry.closePointEps; // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. var points = this.currentPath ? this.currentPath.points : null; if (points) { // TODO: make a better fix. // We check how far our start is from the last existing point var xDiff = Math.abs(points[points.length - 2] - startX); var yDiff = Math.abs(points[points.length - 1] - startY); if (xDiff < eps && yDiff < eps) ; else { points.push(startX, startY); } } else { this.moveTo(startX, startY); points = this.currentPath.points; } ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points); return this; }; /** * Specifies a simple one-color fill that subsequent calls to other Graphics methods * (such as lineTo() or drawCircle()) use when drawing. * * @param {number} [color=0] - the color of the fill * @param {number} [alpha=1] - the alpha of the fill * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.beginFill = function beginFill (color, alpha) { if ( color === void 0 ) color = 0; if ( alpha === void 0 ) alpha = 1; return this.beginTextureFill({ texture: core.Texture.WHITE, color: color, alpha: alpha }); }; /** * Begin the texture fill * * @param {object} [options] - Object object. * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to fill * @param {number} [options.color=0xffffff] - Background to fill behind texture * @param {number} [options.alpha=1] - Alpha of fill * @param {PIXI.Matrix} [options.matrix=null] - Transform matrix * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.beginTextureFill = function beginTextureFill (options) { // backward compatibility with params: (texture, color, alpha, matrix) if (options instanceof core.Texture) { utils.deprecation('v5.2.0', 'Please use object-based options for Graphics#beginTextureFill'); var texture = arguments[0]; var color = arguments[1]; var alpha = arguments[2]; var matrix = arguments[3]; options = { texture: texture, color: color, alpha: alpha, matrix: matrix }; // Remove undefined keys Object.keys(options).forEach(function (key) { return options[key] === undefined && delete options[key]; }); } // Apply defaults options = Object.assign({ texture: core.Texture.WHITE, color: 0xFFFFFF, alpha: 1, matrix: null, }, options); if (this.currentPath) { this.startPoly(); } var visible = options.alpha > 0; if (!visible) { this._fillStyle.reset(); } else { if (options.matrix) { options.matrix = options.matrix.clone(); options.matrix.invert(); } Object.assign(this._fillStyle, { visible: visible }, options); } return this; }; /** * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. * * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.endFill = function endFill () { this.finishPoly(); this._fillStyle.reset(); return this; }; /** * Draws a rectangle shape. * * @param {number} x - The X coord of the top-left of the rectangle * @param {number} y - The Y coord of the top-left of the rectangle * @param {number} width - The width of the rectangle * @param {number} height - The height of the rectangle * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.drawRect = function drawRect (x, y, width, height) { return this.drawShape(new math.Rectangle(x, y, width, height)); }; /** * Draw a rectangle shape with rounded/beveled corners. * * @param {number} x - The X coord of the top-left of the rectangle * @param {number} y - The Y coord of the top-left of the rectangle * @param {number} width - The width of the rectangle * @param {number} height - The height of the rectangle * @param {number} radius - Radius of the rectangle corners * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.drawRoundedRect = function drawRoundedRect (x, y, width, height, radius) { return this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); }; /** * Draws a circle. * * @param {number} x - The X coordinate of the center of the circle * @param {number} y - The Y coordinate of the center of the circle * @param {number} radius - The radius of the circle * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.drawCircle = function drawCircle (x, y, radius) { return this.drawShape(new math.Circle(x, y, radius)); }; /** * Draws an ellipse. * * @param {number} x - The X coordinate of the center of the ellipse * @param {number} y - The Y coordinate of the center of the ellipse * @param {number} width - The half width of the ellipse * @param {number} height - The half height of the ellipse * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.drawEllipse = function drawEllipse (x, y, width, height) { return this.drawShape(new math.Ellipse(x, y, width, height)); }; /** * Draws a polygon using the given path. * * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.drawPolygon = function drawPolygon (path) { var arguments$1 = arguments; // prevents an argument assignment deopt // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments var points = path; var closeStroke = true;// !!this._fillStyle; // check if data has points.. if (points.points) { closeStroke = points.closeStroke; points = points.points; } if (!Array.isArray(points)) { // prevents an argument leak deopt // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments points = new Array(arguments.length); for (var i = 0; i < points.length; ++i) { points[i] = arguments$1[i]; // eslint-disable-line prefer-rest-params } } var shape = new math.Polygon(points); shape.closeStroke = closeStroke; this.drawShape(shape); return this; }; /** * Draw any shape. * * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.drawShape = function drawShape (shape) { if (!this._holeMode) { this.geometry.drawShape( shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix ); } else { this.geometry.drawHole(shape, this._matrix); } return this; }; /** * Draw a star shape with an arbitrary number of points. * * @param {number} x - Center X position of the star * @param {number} y - Center Y position of the star * @param {number} points - The number of points of the star, must be > 1 * @param {number} radius - The outer radius of the star * @param {number} [innerRadius] - The inner radius between points, default half `radius` * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.drawStar = function drawStar (x, y, points, radius, innerRadius, rotation) { if ( rotation === void 0 ) rotation = 0; return this.drawPolygon(new Star(x, y, points, radius, innerRadius, rotation)); }; /** * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. * * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ Graphics.prototype.clear = function clear () { this.geometry.clear(); this._lineStyle.reset(); this._fillStyle.reset(); this._matrix = null; this._holeMode = false; this.currentPath = null; return this; }; /** * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and * masked with gl.scissor. * * @returns {boolean} True if only 1 rect. */ Graphics.prototype.isFastRect = function isFastRect () { return this.geometry.graphicsData.length === 1 && this.geometry.graphicsData[0].shape.type === math.SHAPES.RECT && !this.geometry.graphicsData[0].lineWidth; }; /** * Renders the object using the WebGL renderer * * @protected * @param {PIXI.Renderer} renderer - The renderer */ Graphics.prototype._render = function _render (renderer) { this.finishPoly(); var geometry = this.geometry; // batch part.. // batch it! geometry.updateBatches(); if (geometry.batchable) { if (this.batchDirty !== geometry.batchDirty) { this._populateBatches(); } this._renderBatched(renderer); } else { // no batching... renderer.batch.flush(); this._renderDirect(renderer); } }; /** * Populating batches for rendering * * @protected */ Graphics.prototype._populateBatches = function _populateBatches () { var geometry = this.geometry; var blendMode = this.blendMode; this.batches = []; this.batchTint = -1; this._transformID = -1; this.batchDirty = geometry.batchDirty; this.vertexData = new Float32Array(geometry.points); for (var i = 0, l = geometry.batches.length; i < l; i++) { var gI = geometry.batches[i]; var color = gI.style.color; var vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); var uvs = new Float32Array(geometry.uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); var indices = new Uint16Array(geometry.indicesUint16.buffer, gI.start * 2, gI.size); var batch = { vertexData: vertexData, blendMode: blendMode, indices: indices, uvs: uvs, _batchRGB: utils.hex2rgb(color), _tintRGB: color, _texture: gI.style.texture, alpha: gI.style.alpha, worldAlpha: 1 }; this.batches[i] = batch; } }; /** * Renders the batches using the BathedRenderer plugin * * @protected * @param {PIXI.Renderer} renderer - The renderer */ Graphics.prototype._renderBatched = function _renderBatched (renderer) { if (!this.batches.length) { return; } renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); this.calculateVertices(); this.calculateTints(); for (var i = 0, l = this.batches.length; i < l; i++) { var batch = this.batches[i]; batch.worldAlpha = this.worldAlpha * batch.alpha; renderer.plugins[this.pluginName].render(batch); } }; /** * Renders the graphics direct * * @protected * @param {PIXI.Renderer} renderer - The renderer */ Graphics.prototype._renderDirect = function _renderDirect (renderer) { var shader = this._resolveDirectShader(renderer); var geometry = this.geometry; var tint = this.tint; var worldAlpha = this.worldAlpha; var uniforms = shader.uniforms; var drawCalls = geometry.drawCalls; // lets set the transfomr uniforms.translationMatrix = this.transform.worldTransform; // and then lets set the tint.. uniforms.tint[0] = (((tint >> 16) & 0xFF) / 255) * worldAlpha; uniforms.tint[1] = (((tint >> 8) & 0xFF) / 255) * worldAlpha; uniforms.tint[2] = ((tint & 0xFF) / 255) * worldAlpha; uniforms.tint[3] = worldAlpha; // the first draw call, we can set the uniforms of the shader directly here. // this means that we can tack advantage of the sync function of pixi! // bind and sync uniforms.. // there is a way to optimise this.. renderer.shader.bind(shader); renderer.geometry.bind(geometry, shader); // set state.. renderer.state.set(this.state); // then render the rest of them... for (var i = 0, l = drawCalls.length; i < l; i++) { this._renderDrawCallDirect(renderer, geometry.drawCalls[i]); } }; /** * Renders specific DrawCall * * @param {PIXI.Renderer} renderer * @param {PIXI.BatchDrawCall} drawCall */ Graphics.prototype._renderDrawCallDirect = function _renderDrawCallDirect (renderer, drawCall) { var textures = drawCall.textures; var type = drawCall.type; var size = drawCall.size; var start = drawCall.start; var groupTextureCount = textures.count; for (var j = 0; j < groupTextureCount; j++) { renderer.texture.bind(textures.elements[j], j); } renderer.geometry.draw(type, size, start); }; /** * Resolves shader for direct rendering * * @protected * @param {PIXI.Renderer} renderer - The renderer */ Graphics.prototype._resolveDirectShader = function _resolveDirectShader (renderer) { var shader = this.shader; var pluginName = this.pluginName; if (!shader) { // if there is no shader here, we can use the default shader. // and that only gets created if we actually need it.. // but may be more than one plugins for graphics if (!DEFAULT_SHADERS[pluginName]) { var sampleValues = new Int32Array(16); for (var i = 0; i < 16; i++) { sampleValues[i] = i; } var uniforms = { tint: new Float32Array([1, 1, 1, 1]), translationMatrix: new math.Matrix(), default: core.UniformGroup.from({ uSamplers: sampleValues }, true), }; var program = renderer.plugins[pluginName]._shader.program; DEFAULT_SHADERS[pluginName] = new core.Shader(program, uniforms); } shader = DEFAULT_SHADERS[pluginName]; } return shader; }; /** * Retrieves the bounds of the graphic shape as a rectangle object * * @protected */ Graphics.prototype._calculateBounds = function _calculateBounds () { this.finishPoly(); var geometry = this.geometry; // skipping when graphics is empty, like a container if (!geometry.graphicsData.length) { return; } var ref = geometry.bounds; var minX = ref.minX; var minY = ref.minY; var maxX = ref.maxX; var maxY = ref.maxY; this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); }; /** * Tests if a point is inside this graphics object * * @param {PIXI.Point} point - the point to test * @return {boolean} the result of the test */ Graphics.prototype.containsPoint = function containsPoint (point) { this.worldTransform.applyInverse(point, Graphics._TEMP_POINT); return this.geometry.containsPoint(Graphics._TEMP_POINT); }; /** * Recalcuate the tint by applying tin to batches using Graphics tint. * @protected */ Graphics.prototype.calculateTints = function calculateTints () { if (this.batchTint !== this.tint) { this.batchTint = this.tint; var tintRGB = utils.hex2rgb(this.tint, temp); for (var i = 0; i < this.batches.length; i++) { var batch = this.batches[i]; var batchTint = batch._batchRGB; var r = (tintRGB[0] * batchTint[0]) * 255; var g = (tintRGB[1] * batchTint[1]) * 255; var b = (tintRGB[2] * batchTint[2]) * 255; // TODO Ivan, can this be done in one go? var color = (r << 16) + (g << 8) + (b | 0); batch._tintRGB = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16); } } }; /** * If there's a transform update or a change to the shape of the * geometry, recaculate the vertices. * @protected */ Graphics.prototype.calculateVertices = function calculateVertices () { if (this._transformID === this.transform._worldID) { return; } this._transformID = this.transform._worldID; var wt = this.transform.worldTransform; var a = wt.a; var b = wt.b; var c = wt.c; var d = wt.d; var tx = wt.tx; var ty = wt.ty; var data = this.geometry.points;// batch.vertexDataOriginal; var vertexData = this.vertexData; var count = 0; for (var i = 0; i < data.length; i += 2) { var x = data[i]; var y = data[i + 1]; vertexData[count++] = (a * x) + (c * y) + tx; vertexData[count++] = (d * y) + (b * x) + ty; } }; /** * Closes the current path. * * @return {PIXI.Graphics} Returns itself. */ Graphics.prototype.closePath = function closePath () { var currentPath = this.currentPath; if (currentPath) { // we don't need to add extra point in the end because buildLine will take care of that currentPath.closeStroke = true; } return this; }; /** * Apply a matrix to the positional data. * * @param {PIXI.Matrix} matrix - Matrix to use for transform current shape. * @return {PIXI.Graphics} Returns itself. */ Graphics.prototype.setMatrix = function setMatrix (matrix) { this._matrix = matrix; return this; }; /** * Begin adding holes to the last draw shape * IMPORTANT: holes must be fully inside a shape to work * Also weirdness ensues if holes overlap! * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer, * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle. * @return {PIXI.Graphics} Returns itself. */ Graphics.prototype.beginHole = function beginHole () { this.finishPoly(); this._holeMode = true; return this; }; /** * End adding holes to the last draw shape * @return {PIXI.Graphics} Returns itself. */ Graphics.prototype.endHole = function endHole () { this.finishPoly(); this._holeMode = false; return this; }; /** * Destroys the Graphics object. * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all * options have been set to that value * @param {boolean} [options.children=false] - if set to true, all the children will have * their destroy method called as well. 'options' will be passed on to those calls. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true * Should it destroy the texture of the child sprite * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true * Should it destroy the base texture of the child sprite */ Graphics.prototype.destroy = function destroy (options) { Container.prototype.destroy.call(this, options); this.geometry.refCount--; if (this.geometry.refCount === 0) { this.geometry.dispose(); } this._matrix = null; this.currentPath = null; this._lineStyle.destroy(); this._lineStyle = null; this._fillStyle.destroy(); this._fillStyle = null; this.geometry = null; this.shader = null; this.vertexData = null; this.batches.length = 0; this.batches = null; Container.prototype.destroy.call(this, options); }; Object.defineProperties( Graphics.prototype, prototypeAccessors ); return Graphics; }(display.Container)); /** * Temporary point to use for containsPoint * * @static * @private * @member {PIXI.Point} */ Graphics._TEMP_POINT = new math.Point(); exports.FillStyle = FillStyle; exports.GRAPHICS_CURVES = GRAPHICS_CURVES; exports.Graphics = Graphics; exports.GraphicsData = GraphicsData; exports.GraphicsGeometry = GraphicsGeometry; exports.LineStyle = LineStyle; exports.graphicsUtils = index; },{"@pixi/constants":6,"@pixi/core":7,"@pixi/display":8,"@pixi/math":21,"@pixi/utils":39}],19:[function(require,module,exports){ /*! * @pixi/interaction - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/interaction is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var math = require('@pixi/math'); var ticker = require('@pixi/ticker'); var display = require('@pixi/display'); var utils = require('@pixi/utils'); /** * Holds all information related to an Interaction event * * @class * @memberof PIXI.interaction */ var InteractionData = function InteractionData() { /** * This point stores the global coords of where the touch/mouse event happened * * @member {PIXI.Point} */ this.global = new math.Point(); /** * The target Sprite that was interacted with * * @member {PIXI.Sprite} */ this.target = null; /** * When passed to an event handler, this will be the original DOM Event that was captured * * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent * @member {MouseEvent|TouchEvent|PointerEvent} */ this.originalEvent = null; /** * Unique identifier for this interaction * * @member {number} */ this.identifier = null; /** * Indicates whether or not the pointer device that created the event is the primary pointer. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary * @type {Boolean} */ this.isPrimary = false; /** * Indicates which button was pressed on the mouse or pointer device to trigger the event. * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button * @type {number} */ this.button = 0; /** * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons * @type {number} */ this.buttons = 0; /** * The width of the pointer's contact along the x-axis, measured in CSS pixels. * radiusX of TouchEvents will be represented by this value. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width * @type {number} */ this.width = 0; /** * The height of the pointer's contact along the y-axis, measured in CSS pixels. * radiusY of TouchEvents will be represented by this value. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height * @type {number} */ this.height = 0; /** * The angle, in degrees, between the pointer device and the screen. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX * @type {number} */ this.tiltX = 0; /** * The angle, in degrees, between the pointer device and the screen. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY * @type {number} */ this.tiltY = 0; /** * The type of pointer that triggered the event. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType * @type {string} */ this.pointerType = null; /** * Pressure applied by the pointing device during the event. A Touch's force property * will be represented by this value. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure * @type {number} */ this.pressure = 0; /** * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle * @type {number} */ this.rotationAngle = 0; /** * Twist of a stylus pointer. * @see https://w3c.github.io/pointerevents/#pointerevent-interface * @type {number} */ this.twist = 0; /** * Barrel pressure on a stylus pointer. * @see https://w3c.github.io/pointerevents/#pointerevent-interface * @type {number} */ this.tangentialPressure = 0; }; var prototypeAccessors = { pointerId: { configurable: true } }; /** * The unique identifier of the pointer. It will be the same as `identifier`. * @readonly * @member {number} * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId */ prototypeAccessors.pointerId.get = function () { return this.identifier; }; /** * This will return the local coordinates of the specified displayObject for this InteractionData * * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local * coords off * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise * will create a new point) * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional * (otherwise will use the current global coords) * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative * to the DisplayObject */ InteractionData.prototype.getLocalPosition = function getLocalPosition (displayObject, point, globalPos) { return displayObject.worldTransform.applyInverse(globalPos || this.global, point); }; /** * Copies properties from normalized event data. * * @param {Touch|MouseEvent|PointerEvent} event The normalized event data */ InteractionData.prototype.copyEvent = function copyEvent (event) { // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite // it with "false" on later events when our shim for it on touch events might not be // accurate if (event.isPrimary) { this.isPrimary = true; } this.button = event.button; // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard // event.which property instead, which conveys the same information. this.buttons = Number.isInteger(event.buttons) ? event.buttons : event.which; this.width = event.width; this.height = event.height; this.tiltX = event.tiltX; this.tiltY = event.tiltY; this.pointerType = event.pointerType; this.pressure = event.pressure; this.rotationAngle = event.rotationAngle; this.twist = event.twist || 0; this.tangentialPressure = event.tangentialPressure || 0; }; /** * Resets the data for pooling. */ InteractionData.prototype.reset = function reset () { // isPrimary is the only property that we really need to reset - everything else is // guaranteed to be overwritten this.isPrimary = false; }; Object.defineProperties( InteractionData.prototype, prototypeAccessors ); /** * Event class that mimics native DOM events. * * @class * @memberof PIXI.interaction */ var InteractionEvent = function InteractionEvent() { /** * Whether this event will continue propagating in the tree. * * Remaining events for the {@link stopsPropagatingAt} object * will still be dispatched. * * @member {boolean} */ this.stopped = false; /** * At which object this event stops propagating. * * @private * @member {PIXI.DisplayObject} */ this.stopsPropagatingAt = null; /** * Whether we already reached the element we want to * stop propagating at. This is important for delayed events, * where we start over deeper in the tree again. * * @private * @member {boolean} */ this.stopPropagationHint = false; /** * The object which caused this event to be dispatched. * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. * * @member {PIXI.DisplayObject} */ this.target = null; /** * The object whose event listener’s callback is currently being invoked. * * @member {PIXI.DisplayObject} */ this.currentTarget = null; /** * Type of the event * * @member {string} */ this.type = null; /** * InteractionData related to this event * * @member {PIXI.interaction.InteractionData} */ this.data = null; }; /** * Prevents event from reaching any objects other than the current object. * */ InteractionEvent.prototype.stopPropagation = function stopPropagation () { this.stopped = true; this.stopPropagationHint = true; this.stopsPropagatingAt = this.currentTarget; }; /** * Resets the event. */ InteractionEvent.prototype.reset = function reset () { this.stopped = false; this.stopsPropagatingAt = null; this.stopPropagationHint = false; this.currentTarget = null; this.target = null; }; /** * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions * * @class * @private * @memberof PIXI.interaction */ var InteractionTrackingData = function InteractionTrackingData(pointerId) { this._pointerId = pointerId; this._flags = InteractionTrackingData.FLAGS.NONE; }; var prototypeAccessors$1 = { pointerId: { configurable: true },flags: { configurable: true },none: { configurable: true },over: { configurable: true },rightDown: { configurable: true },leftDown: { configurable: true } }; /** * * @private * @param {number} flag - The interaction flag to set * @param {boolean} yn - Should the flag be set or unset */ InteractionTrackingData.prototype._doSet = function _doSet (flag, yn) { if (yn) { this._flags = this._flags | flag; } else { this._flags = this._flags & (~flag); } }; /** * Unique pointer id of the event * * @readonly * @private * @member {number} */ prototypeAccessors$1.pointerId.get = function () { return this._pointerId; }; /** * State of the tracking data, expressed as bit flags * * @private * @member {number} */ prototypeAccessors$1.flags.get = function () { return this._flags; }; prototypeAccessors$1.flags.set = function (flags) // eslint-disable-line require-jsdoc { this._flags = flags; }; /** * Is the tracked event inactive (not over or down)? * * @private * @member {number} */ prototypeAccessors$1.none.get = function () { return this._flags === this.constructor.FLAGS.NONE; }; /** * Is the tracked event over the DisplayObject? * * @private * @member {boolean} */ prototypeAccessors$1.over.get = function () { return (this._flags & this.constructor.FLAGS.OVER) !== 0; }; prototypeAccessors$1.over.set = function (yn) // eslint-disable-line require-jsdoc { this._doSet(this.constructor.FLAGS.OVER, yn); }; /** * Did the right mouse button come down in the DisplayObject? * * @private * @member {boolean} */ prototypeAccessors$1.rightDown.get = function () { return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; }; prototypeAccessors$1.rightDown.set = function (yn) // eslint-disable-line require-jsdoc { this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); }; /** * Did the left mouse button come down in the DisplayObject? * * @private * @member {boolean} */ prototypeAccessors$1.leftDown.get = function () { return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; }; prototypeAccessors$1.leftDown.set = function (yn) // eslint-disable-line require-jsdoc { this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); }; Object.defineProperties( InteractionTrackingData.prototype, prototypeAccessors$1 ); InteractionTrackingData.FLAGS = Object.freeze({ NONE: 0, OVER: 1 << 0, LEFT_DOWN: 1 << 1, RIGHT_DOWN: 1 << 2, }); /** * Strategy how to search through stage tree for interactive objects * * @private * @class * @memberof PIXI.interaction */ var TreeSearch = function TreeSearch() { this._tempPoint = new math.Point(); }; /** * Recursive implementation for findHit * * @private * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that * is tested for collision * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject * that will be hit test (recursively crawls its children) * @param {Function} [func] - the function that will be called on each interactive object. The * interactionEvent, displayObject and hit will be passed to the function * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point * @param {boolean} [interactive] - Whether the displayObject is interactive * @return {boolean} returns true if the displayObject hit the point */ TreeSearch.prototype.recursiveFindHit = function recursiveFindHit (interactionEvent, displayObject, func, hitTest, interactive) { if (!displayObject || !displayObject.visible) { return false; } var point = interactionEvent.data.global; // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^ // // This function will now loop through all objects and then only hit test the objects it HAS // to, not all of them. MUCH faster.. // An object will be hit test if the following is true: // // 1: It is interactive. // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. // // As another little optimization once an interactive object has been hit we can carry on // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests // A final optimization is that an object is not hit test directly if a child has already been hit. interactive = displayObject.interactive || interactive; var hit = false; var interactiveParent = interactive; // Flag here can set to false if the event is outside the parents hitArea or mask var hitTestChildren = true; // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea // There is also no longer a need to hitTest children. if (displayObject.hitArea) { if (hitTest) { displayObject.worldTransform.applyInverse(point, this._tempPoint); if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { hitTest = false; hitTestChildren = false; } else { hit = true; } } interactiveParent = false; } // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask. // We still want to hitTestChildren, however, to ensure a mouseout can still be generated. // https://github.com/pixijs/pixi.js/issues/5135 else if (displayObject._mask) { if (hitTest) { if (!(displayObject._mask.containsPoint && displayObject._mask.containsPoint(point))) { hitTest = false; } } } // ** FREE TIP **! If an object is not interactive or has no buttons in it // (such as a game scene!) set interactiveChildren to false for that displayObject. // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { var children = displayObject.children; for (var i = children.length - 1; i >= 0; i--) { var child = children[i]; // time to get recursive.. if this function will return if something is hit.. var childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent); if (childHit) { // its a good idea to check if a child has lost its parent. // this means it has been removed whilst looping so its best if (!child.parent) { continue; } // we no longer need to hit test any more objects in this container as we we // now know the parent has been hit interactiveParent = false; // If the child is interactive , that means that the object hit was actually // interactive and not just the child of an interactive object. // This means we no longer need to hit test anything else. We still need to run // through all objects, but we don't need to perform any hit tests. if (childHit) { if (interactionEvent.target) { hitTest = false; } hit = true; } } } } // no point running this if the item is not interactive or does not have an interactive parent. if (interactive) { // if we are hit testing (as in we have no hit any objects yet) // We also don't need to worry about hit testing if once of the displayObjects children // has already been hit - but only if it was interactive, otherwise we need to keep // looking for an interactive child, just in case we hit one if (hitTest && !interactionEvent.target) { // already tested against hitArea if it is defined if (!displayObject.hitArea && displayObject.containsPoint) { if (displayObject.containsPoint(point)) { hit = true; } } } if (displayObject.interactive) { if (hit && !interactionEvent.target) { interactionEvent.target = displayObject; } if (func) { func(interactionEvent, displayObject, !!hit); } } } return hit; }; /** * This function is provides a neat way of crawling through the scene graph and running a * specified function on all interactive objects it finds. It will also take care of hit * testing the interactive objects and passes the hit across in the function. * * @private * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that * is tested for collision * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject * that will be hit test (recursively crawls its children) * @param {Function} [func] - the function that will be called on each interactive object. The * interactionEvent, displayObject and hit will be passed to the function * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point * @return {boolean} returns true if the displayObject hit the point */ TreeSearch.prototype.findHit = function findHit (interactionEvent, displayObject, func, hitTest) { this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false); }; /** * Interface for classes that represent a hit area. * * It is implemented by the following classes: * - {@link PIXI.Circle} * - {@link PIXI.Ellipse} * - {@link PIXI.Polygon} * - {@link PIXI.RoundedRectangle} * * @interface IHitArea * @memberof PIXI */ /** * Checks whether the x and y coordinates given are contained within this area * * @method * @name contains * @memberof PIXI.IHitArea# * @param {number} x - The X coordinate of the point to test * @param {number} y - The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this area */ /** * Default property values of interactive objects * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties * * @private * @name interactiveTarget * @type {Object} * @memberof PIXI.interaction * @example * function MyObject() {} * * Object.assign( * DisplayObject.prototype, * PIXI.interaction.interactiveTarget * ); */ var interactiveTarget = { /** * Enable interaction events for the DisplayObject. Touch, pointer and mouse * events will not be emitted unless `interactive` is set to `true`. * * @example * const sprite = new PIXI.Sprite(texture); * sprite.interactive = true; * sprite.on('tap', (event) => { * //handle event * }); * @member {boolean} * @memberof PIXI.DisplayObject# */ interactive: false, /** * Determines if the children to the displayObject can be clicked/touched * Setting this to false allows PixiJS to bypass a recursive `hitTest` function * * @member {boolean} * @memberof PIXI.Container# */ interactiveChildren: true, /** * Interaction shape. Children will be hit first, then this shape will be checked. * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. * * @example * const sprite = new PIXI.Sprite(texture); * sprite.interactive = true; * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); * @member {PIXI.IHitArea} * @memberof PIXI.DisplayObject# */ hitArea: null, /** * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive * Setting this changes the 'cursor' property to `'pointer'`. * * @example * const sprite = new PIXI.Sprite(texture); * sprite.interactive = true; * sprite.buttonMode = true; * @member {boolean} * @memberof PIXI.DisplayObject# */ get buttonMode() { return this.cursor === 'pointer'; }, set buttonMode(value) { if (value) { this.cursor = 'pointer'; } else if (this.cursor === 'pointer') { this.cursor = null; } }, /** * This defines what cursor mode is used when the mouse cursor * is hovered over the displayObject. * * @example * const sprite = new PIXI.Sprite(texture); * sprite.interactive = true; * sprite.cursor = 'wait'; * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor * * @member {string} * @memberof PIXI.DisplayObject# */ cursor: null, /** * Internal set of all active pointers, by identifier * * @member {Map} * @memberof PIXI.DisplayObject# * @private */ get trackedPointers() { if (this._trackedPointers === undefined) { this._trackedPointers = {}; } return this._trackedPointers; }, /** * Map of all tracked pointers, by identifier. Use trackedPointers to access. * * @private * @type {Map} */ _trackedPointers: undefined, }; // Mix interactiveTarget into DisplayObject.prototype, // after deprecation has been handled display.DisplayObject.mixin(interactiveTarget); var MOUSE_POINTER_ID = 1; // helpers for hitTest() - only used inside hitTest() var hitTestEvent = { target: null, data: { global: null, }, }; /** * The interaction manager deals with mouse, touch and pointer events. * * Any DisplayObject can be interactive if its `interactive` property is set to true. * * This manager also supports multitouch. * * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction` * * @class * @extends PIXI.utils.EventEmitter * @memberof PIXI.interaction */ var InteractionManager = /*@__PURE__*/(function (EventEmitter) { function InteractionManager(renderer, options) { EventEmitter.call(this); options = options || {}; /** * The renderer this interaction manager works for. * * @member {PIXI.AbstractRenderer} */ this.renderer = renderer; /** * Should default browser actions automatically be prevented. * Does not apply to pointer events for backwards compatibility * preventDefault on pointer events stops mouse events from firing * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. * * @member {boolean} * @default true */ this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; /** * Maximum requency in milliseconds at which pointer over/out states will be checked by {@link tickerUpdate}. * * @member {number} * @default 10 */ this.interactionFrequency = options.interactionFrequency || 10; /** * The mouse data * * @member {PIXI.interaction.InteractionData} */ this.mouse = new InteractionData(); this.mouse.identifier = MOUSE_POINTER_ID; // setting the mouse to start off far off screen will mean that mouse over does // not get called before we even move the mouse. this.mouse.global.set(-999999); /** * Actively tracked InteractionData * * @private * @member {Object.} */ this.activeInteractionData = {}; this.activeInteractionData[MOUSE_POINTER_ID] = this.mouse; /** * Pool of unused InteractionData * * @private * @member {PIXI.interaction.InteractionData[]} */ this.interactionDataPool = []; /** * An event data object to handle all the event tracking/dispatching * * @member {object} */ this.eventData = new InteractionEvent(); /** * The DOM element to bind to. * * @protected * @member {HTMLElement} */ this.interactionDOMElement = null; /** * This property determines if mousemove and touchmove events are fired only when the cursor * is over the object. * Setting to true will make things work more in line with how the DOM version works. * Setting to false can make things easier for things like dragging * It is currently set to false as this is how PixiJS used to work. This will be set to true in * future versions of pixi. * * @member {boolean} * @default false */ this.moveWhenInside = false; /** * Have events been attached to the dom element? * * @protected * @member {boolean} */ this.eventsAdded = false; /** * Has the system ticker been added? * * @protected * @member {boolean} */ this.tickerAdded = false; /** * Is the mouse hovering over the renderer? * * @protected * @member {boolean} */ this.mouseOverRenderer = false; /** * Does the device support touch events * https://www.w3.org/TR/touch-events/ * * @readonly * @member {boolean} */ this.supportsTouchEvents = 'ontouchstart' in window; /** * Does the device support pointer events * https://www.w3.org/Submission/pointer-events/ * * @readonly * @member {boolean} */ this.supportsPointerEvents = !!window.PointerEvent; // this will make it so that you don't have to call bind all the time /** * @private * @member {Function} */ this.onPointerUp = this.onPointerUp.bind(this); this.processPointerUp = this.processPointerUp.bind(this); /** * @private * @member {Function} */ this.onPointerCancel = this.onPointerCancel.bind(this); this.processPointerCancel = this.processPointerCancel.bind(this); /** * @private * @member {Function} */ this.onPointerDown = this.onPointerDown.bind(this); this.processPointerDown = this.processPointerDown.bind(this); /** * @private * @member {Function} */ this.onPointerMove = this.onPointerMove.bind(this); this.processPointerMove = this.processPointerMove.bind(this); /** * @private * @member {Function} */ this.onPointerOut = this.onPointerOut.bind(this); this.processPointerOverOut = this.processPointerOverOut.bind(this); /** * @private * @member {Function} */ this.onPointerOver = this.onPointerOver.bind(this); /** * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor * values, objects are handled as dictionaries of CSS values for interactionDOMElement, * and functions are called instead of changing the CSS. * Default CSS cursor values are provided for 'default' and 'pointer' modes. * @member {Object.} */ this.cursorStyles = { default: 'inherit', pointer: 'pointer', }; /** * The mode of the cursor that is being used. * The value of this is a key from the cursorStyles dictionary. * * @member {string} */ this.currentCursorMode = null; /** * Internal cached let. * * @private * @member {string} */ this.cursor = null; /** * The current resolution / device pixel ratio. * * @member {number} * @default 1 */ this.resolution = 1; /** * Delayed pointer events. Used to guarantee correct ordering of over/out events. * * @private * @member {Array} */ this.delayedEvents = []; /** * TreeSearch component that is used to hitTest stage tree * * @private * @member {PIXI.interaction.TreeSearch} */ this.search = new TreeSearch(); /** * Fired when a pointer device button (usually a mouse left-button) is pressed on the display * object. * * @event PIXI.interaction.InteractionManager#mousedown * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device secondary button (usually a mouse right-button) is pressed * on the display object. * * @event PIXI.interaction.InteractionManager#rightdown * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button (usually a mouse left-button) is released over the display * object. * * @event PIXI.interaction.InteractionManager#mouseup * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device secondary button (usually a mouse right-button) is released * over the display object. * * @event PIXI.interaction.InteractionManager#rightup * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button (usually a mouse left-button) is pressed and released on * the display object. * * @event PIXI.interaction.InteractionManager#click * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device secondary button (usually a mouse right-button) is pressed * and released on the display object. * * @event PIXI.interaction.InteractionManager#rightclick * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button (usually a mouse left-button) is released outside the * display object that initially registered a * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. * * @event PIXI.interaction.InteractionManager#mouseupoutside * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device secondary button (usually a mouse right-button) is released * outside the display object that initially registered a * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. * * @event PIXI.interaction.InteractionManager#rightupoutside * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device (usually a mouse) is moved while over the display object * * @event PIXI.interaction.InteractionManager#mousemove * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device (usually a mouse) is moved onto the display object * * @event PIXI.interaction.InteractionManager#mouseover * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device (usually a mouse) is moved off the display object * * @event PIXI.interaction.InteractionManager#mouseout * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button is pressed on the display object. * * @event PIXI.interaction.InteractionManager#pointerdown * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button is released over the display object. * Not always fired when some buttons are held down while others are released. In those cases, * use [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown} and * [mouseup]{@link PIXI.interaction.InteractionManager#event:mouseup} instead. * * @event PIXI.interaction.InteractionManager#pointerup * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when the operating system cancels a pointer event * * @event PIXI.interaction.InteractionManager#pointercancel * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button is pressed and released on the display object. * * @event PIXI.interaction.InteractionManager#pointertap * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button is released outside the display object that initially * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. * * @event PIXI.interaction.InteractionManager#pointerupoutside * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device is moved while over the display object * * @event PIXI.interaction.InteractionManager#pointermove * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device is moved onto the display object * * @event PIXI.interaction.InteractionManager#pointerover * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device is moved off the display object * * @event PIXI.interaction.InteractionManager#pointerout * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a touch point is placed on the display object. * * @event PIXI.interaction.InteractionManager#touchstart * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a touch point is removed from the display object. * * @event PIXI.interaction.InteractionManager#touchend * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when the operating system cancels a touch * * @event PIXI.interaction.InteractionManager#touchcancel * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a touch point is placed and removed from the display object. * * @event PIXI.interaction.InteractionManager#tap * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a touch point is removed outside of the display object that initially * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. * * @event PIXI.interaction.InteractionManager#touchendoutside * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a touch point is moved along the display object. * * @event PIXI.interaction.InteractionManager#touchmove * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. * object. DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#mousedown * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device secondary button (usually a mouse right-button) is pressed * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#rightdown * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button (usually a mouse left-button) is released over the display * object. DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#mouseup * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device secondary button (usually a mouse right-button) is released * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#rightup * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button (usually a mouse left-button) is pressed and released on * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#click * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device secondary button (usually a mouse right-button) is pressed * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#rightclick * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button (usually a mouse left-button) is released outside the * display object that initially registered a * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#mouseupoutside * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device secondary button (usually a mouse right-button) is released * outside the display object that initially registered a * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#rightupoutside * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device (usually a mouse) is moved while over the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#mousemove * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device (usually a mouse) is moved onto the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#mouseover * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device (usually a mouse) is moved off the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#mouseout * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button is pressed on the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#pointerdown * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button is released over the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#pointerup * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when the operating system cancels a pointer event. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#pointercancel * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button is pressed and released on the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#pointertap * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device button is released outside the display object that initially * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#pointerupoutside * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device is moved while over the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#pointermove * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device is moved onto the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#pointerover * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a pointer device is moved off the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#pointerout * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a touch point is placed on the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#touchstart * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a touch point is removed from the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#touchend * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when the operating system cancels a touch. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#touchcancel * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a touch point is placed and removed from the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#tap * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a touch point is removed outside of the display object that initially * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#touchendoutside * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ /** * Fired when a touch point is moved along the display object. * DisplayObject's `interactive` property must be set to `true` to fire event. * * @event PIXI.DisplayObject#touchmove * @param {PIXI.interaction.InteractionEvent} event - Interaction event */ this._useSystemTicker = options.useSystemTicker !== undefined ? options.useSystemTicker : true; this.setTargetElement(this.renderer.view, this.renderer.resolution); } if ( EventEmitter ) InteractionManager.__proto__ = EventEmitter; InteractionManager.prototype = Object.create( EventEmitter && EventEmitter.prototype ); InteractionManager.prototype.constructor = InteractionManager; var prototypeAccessors = { useSystemTicker: { configurable: true } }; /** * Should the InteractionManager automatically add {@link tickerUpdate} to {@link PIXI.Ticker.system}. * * @member {boolean} * @default true */ prototypeAccessors.useSystemTicker.get = function () { return this._useSystemTicker; }; prototypeAccessors.useSystemTicker.set = function (useSystemTicker) { this._useSystemTicker = useSystemTicker; if (useSystemTicker) { this.addTickerListener(); } else { this.removeTickerListener(); } }; /** * Hit tests a point against the display tree, returning the first interactive object that is hit. * * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults * to the last rendered root of the associated renderer. * @return {PIXI.DisplayObject} The hit display object, if any. */ InteractionManager.prototype.hitTest = function hitTest (globalPoint, root) { // clear the target for our hit test hitTestEvent.target = null; // assign the global point hitTestEvent.data.global = globalPoint; // ensure safety of the root if (!root) { root = this.renderer._lastObjectRendered; } // run the hit test this.processInteractive(hitTestEvent, root, null, true); // return our found object - it'll be null if we didn't hit anything return hitTestEvent.target; }; /** * Sets the DOM element which will receive mouse/touch events. This is useful for when you have * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate * another DOM element to receive those events. * * @param {HTMLElement} element - the DOM element which will receive mouse and touch events. * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). */ InteractionManager.prototype.setTargetElement = function setTargetElement (element, resolution) { if ( resolution === void 0 ) resolution = 1; this.removeTickerListener(); this.removeEvents(); this.interactionDOMElement = element; this.resolution = resolution; this.addEvents(); this.addTickerListener(); }; /** * Add the ticker listener * * @private */ InteractionManager.prototype.addTickerListener = function addTickerListener () { if (this.tickerAdded || !this.interactionDOMElement || !this._useSystemTicker) { return; } ticker.Ticker.system.add(this.tickerUpdate, this, ticker.UPDATE_PRIORITY.INTERACTION); this.tickerAdded = true; }; /** * Remove the ticker listener * * @private */ InteractionManager.prototype.removeTickerListener = function removeTickerListener () { if (!this.tickerAdded) { return; } ticker.Ticker.system.remove(this.tickerUpdate, this); this.tickerAdded = false; }; /** * Registers all the DOM events * * @private */ InteractionManager.prototype.addEvents = function addEvents () { if (this.eventsAdded || !this.interactionDOMElement) { return; } if (window.navigator.msPointerEnabled) { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } else if (this.supportsPointerEvents) { this.interactionDOMElement.style['touch-action'] = 'none'; } /** * These events are added first, so that if pointer events are normalized, they are fired * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd */ if (this.supportsPointerEvents) { window.document.addEventListener('pointermove', this.onPointerMove, true); this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); // pointerout is fired in addition to pointerup (for touch events) and pointercancel // we already handle those, so for the purposes of what we do in onPointerOut, we only // care about the pointerleave event this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); window.addEventListener('pointercancel', this.onPointerCancel, true); window.addEventListener('pointerup', this.onPointerUp, true); } else { window.document.addEventListener('mousemove', this.onPointerMove, true); this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); window.addEventListener('mouseup', this.onPointerUp, true); } // always look directly for touch events so that we can provide original data // In a future version we should change this to being just a fallback and rely solely on // PointerEvents whenever available if (this.supportsTouchEvents) { this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); } this.eventsAdded = true; }; /** * Removes all the DOM events that were previously registered * * @private */ InteractionManager.prototype.removeEvents = function removeEvents () { if (!this.eventsAdded || !this.interactionDOMElement) { return; } if (window.navigator.msPointerEnabled) { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } else if (this.supportsPointerEvents) { this.interactionDOMElement.style['touch-action'] = ''; } if (this.supportsPointerEvents) { window.document.removeEventListener('pointermove', this.onPointerMove, true); this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); window.removeEventListener('pointercancel', this.onPointerCancel, true); window.removeEventListener('pointerup', this.onPointerUp, true); } else { window.document.removeEventListener('mousemove', this.onPointerMove, true); this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); window.removeEventListener('mouseup', this.onPointerUp, true); } if (this.supportsTouchEvents) { this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); } this.interactionDOMElement = null; this.eventsAdded = false; }; /** * Updates the state of interactive objects if at least {@link interactionFrequency} * milliseconds have passed since the last invocation. * * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}. * * @param {number} deltaTime - time delta since the last call */ InteractionManager.prototype.tickerUpdate = function tickerUpdate (deltaTime) { this._deltaTime += deltaTime; if (this._deltaTime < this.interactionFrequency) { return; } this._deltaTime = 0; this.update(); }; /** * Updates the state of interactive objects. */ InteractionManager.prototype.update = function update () { if (!this.interactionDOMElement) { return; } // if the user move the mouse this check has already been done using the mouse move! if (this.didMove) { this.didMove = false; return; } this.cursor = null; // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, // but there was a scenario of a display object moving under a static mouse cursor. // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function for (var k in this.activeInteractionData) { // eslint-disable-next-line no-prototype-builtins if (this.activeInteractionData.hasOwnProperty(k)) { var interactionData = this.activeInteractionData[k]; if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { var interactionEvent = this.configureInteractionEventForDOMEvent( this.eventData, interactionData.originalEvent, interactionData ); this.processInteractive( interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true ); } } } this.setCursorMode(this.cursor); }; /** * Sets the current cursor mode, handling any callbacks or CSS style changes. * * @param {string} mode - cursor mode, a key from the cursorStyles dictionary */ InteractionManager.prototype.setCursorMode = function setCursorMode (mode) { mode = mode || 'default'; // if the mode didn't actually change, bail early if (this.currentCursorMode === mode) { return; } this.currentCursorMode = mode; var style = this.cursorStyles[mode]; // only do things if there is a cursor style for it if (style) { switch (typeof style) { case 'string': // string styles are handled as cursor CSS this.interactionDOMElement.style.cursor = style; break; case 'function': // functions are just called, and passed the cursor mode style(mode); break; case 'object': // if it is an object, assume that it is a dictionary of CSS styles, // apply it to the interactionDOMElement Object.assign(this.interactionDOMElement.style, style); break; } } else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry // for the mode, then assume that the dev wants it to be CSS for the cursor. this.interactionDOMElement.style.cursor = mode; } }; /** * Dispatches an event on the display object that was interacted with * * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the display object in question * @param {string} eventString - the name of the event (e.g, mousedown) * @param {object} eventData - the event data object * @private */ InteractionManager.prototype.dispatchEvent = function dispatchEvent (displayObject, eventString, eventData) { // Even if the event was stopped, at least dispatch any remaining events // for the same display object. if (!eventData.stopPropagationHint || displayObject === eventData.stopsPropagatingAt) { eventData.currentTarget = displayObject; eventData.type = eventString; displayObject.emit(eventString, eventData); if (displayObject[eventString]) { displayObject[eventString](eventData); } } }; /** * Puts a event on a queue to be dispatched later. This is used to guarantee correct * ordering of over/out events. * * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the display object in question * @param {string} eventString - the name of the event (e.g, mousedown) * @param {object} eventData - the event data object * @private */ InteractionManager.prototype.delayDispatchEvent = function delayDispatchEvent (displayObject, eventString, eventData) { this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData }); }; /** * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The * resulting value is stored in the point. This takes into account the fact that the DOM * element could be scaled and positioned anywhere on the screen. * * @param {PIXI.Point} point - the point that the result will be stored in * @param {number} x - the x coord of the position to map * @param {number} y - the y coord of the position to map */ InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint (point, x, y) { var rect; // IE 11 fix if (!this.interactionDOMElement.parentElement) { rect = { x: 0, y: 0, width: 0, height: 0 }; } else { rect = this.interactionDOMElement.getBoundingClientRect(); } var resolutionMultiplier = 1.0 / this.resolution; point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier; point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier; }; /** * This function is provides a neat way of crawling through the scene graph and running a * specified function on all interactive objects it finds. It will also take care of hit * testing the interactive objects and passes the hit across in the function. * * @protected * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that * is tested for collision * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject * that will be hit test (recursively crawls its children) * @param {Function} [func] - the function that will be called on each interactive object. The * interactionEvent, displayObject and hit will be passed to the function * @param {boolean} [hitTest] - indicates whether we want to calculate hits * or just iterate through all interactive objects */ InteractionManager.prototype.processInteractive = function processInteractive (interactionEvent, displayObject, func, hitTest) { var hit = this.search.findHit(interactionEvent, displayObject, func, hitTest); var delayedEvents = this.delayedEvents; if (!delayedEvents.length) { return hit; } // Reset the propagation hint, because we start deeper in the tree again. interactionEvent.stopPropagationHint = false; var delayedLen = delayedEvents.length; this.delayedEvents = []; for (var i = 0; i < delayedLen; i++) { var ref = delayedEvents[i]; var displayObject$1 = ref.displayObject; var eventString = ref.eventString; var eventData = ref.eventData; // When we reach the object we wanted to stop propagating at, // set the propagation hint. if (eventData.stopsPropagatingAt === displayObject$1) { eventData.stopPropagationHint = true; } this.dispatchEvent(displayObject$1, eventString, eventData); } return hit; }; /** * Is called when the pointer button is pressed down on the renderer element * * @private * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down */ InteractionManager.prototype.onPointerDown = function onPointerDown (originalEvent) { // if we support touch events, then only use those for touch events, not pointer events if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') { return; } var events = this.normalizeToPointerData(originalEvent); /** * No need to prevent default on natural pointer events, as there are no side effects * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, * so still need to be prevented. */ // Guaranteed that there will be at least one event in events, and all events must have the same pointer type if (this.autoPreventDefault && events[0].isNormalized) { var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent); if (cancelable) { originalEvent.preventDefault(); } } var eventLen = events.length; for (var i = 0; i < eventLen; i++) { var event = events[i]; var interactionData = this.getInteractionDataForPointerId(event); var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); interactionEvent.data.originalEvent = originalEvent; this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); this.emit('pointerdown', interactionEvent); if (event.pointerType === 'touch') { this.emit('touchstart', interactionEvent); } // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { var isRightButton = event.button === 2; this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); } } }; /** * Processes the result of the pointer down check and dispatches the event if need be * * @private * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */ InteractionManager.prototype.processPointerDown = function processPointerDown (interactionEvent, displayObject, hit) { var data = interactionEvent.data; var id = interactionEvent.data.identifier; if (hit) { if (!displayObject.trackedPointers[id]) { displayObject.trackedPointers[id] = new InteractionTrackingData(id); } this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); if (data.pointerType === 'touch') { this.dispatchEvent(displayObject, 'touchstart', interactionEvent); } else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { var isRightButton = data.button === 2; if (isRightButton) { displayObject.trackedPointers[id].rightDown = true; } else { displayObject.trackedPointers[id].leftDown = true; } this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); } } }; /** * Is called when the pointer button is released on the renderer element * * @private * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released * @param {boolean} cancelled - true if the pointer is cancelled * @param {Function} func - Function passed to {@link processInteractive} */ InteractionManager.prototype.onPointerComplete = function onPointerComplete (originalEvent, cancelled, func) { var events = this.normalizeToPointerData(originalEvent); var eventLen = events.length; // if the event wasn't targeting our canvas, then consider it to be pointerupoutside // in all cases (unless it was a pointercancel) var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; for (var i = 0; i < eventLen; i++) { var event = events[i]; var interactionData = this.getInteractionDataForPointerId(event); var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); interactionEvent.data.originalEvent = originalEvent; // perform hit testing for events targeting our canvas or cancel events this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); this.emit(cancelled ? 'pointercancel' : ("pointerup" + eventAppend), interactionEvent); if (event.pointerType === 'mouse' || event.pointerType === 'pen') { var isRightButton = event.button === 2; this.emit(isRightButton ? ("rightup" + eventAppend) : ("mouseup" + eventAppend), interactionEvent); } else if (event.pointerType === 'touch') { this.emit(cancelled ? 'touchcancel' : ("touchend" + eventAppend), interactionEvent); this.releaseInteractionDataForPointerId(event.pointerId, interactionData); } } }; /** * Is called when the pointer button is cancelled * * @private * @param {PointerEvent} event - The DOM event of a pointer button being released */ InteractionManager.prototype.onPointerCancel = function onPointerCancel (event) { // if we support touch events, then only use those for touch events, not pointer events if (this.supportsTouchEvents && event.pointerType === 'touch') { return; } this.onPointerComplete(event, true, this.processPointerCancel); }; /** * Processes the result of the pointer cancel check and dispatches the event if need be * * @private * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested */ InteractionManager.prototype.processPointerCancel = function processPointerCancel (interactionEvent, displayObject) { var data = interactionEvent.data; var id = interactionEvent.data.identifier; if (displayObject.trackedPointers[id] !== undefined) { delete displayObject.trackedPointers[id]; this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); if (data.pointerType === 'touch') { this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); } } }; /** * Is called when the pointer button is released on the renderer element * * @private * @param {PointerEvent} event - The DOM event of a pointer button being released */ InteractionManager.prototype.onPointerUp = function onPointerUp (event) { // if we support touch events, then only use those for touch events, not pointer events if (this.supportsTouchEvents && event.pointerType === 'touch') { return; } this.onPointerComplete(event, false, this.processPointerUp); }; /** * Processes the result of the pointer up check and dispatches the event if need be * * @private * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */ InteractionManager.prototype.processPointerUp = function processPointerUp (interactionEvent, displayObject, hit) { var data = interactionEvent.data; var id = interactionEvent.data.identifier; var trackingData = displayObject.trackedPointers[id]; var isTouch = data.pointerType === 'touch'; var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); // need to track mouse down status in the mouse block so that we can emit // event in a later block var isMouseTap = false; // Mouse only if (isMouse) { var isRightButton = data.button === 2; var flags = InteractionTrackingData.FLAGS; var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; var isDown = trackingData !== undefined && (trackingData.flags & test); if (hit) { this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); if (isDown) { this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap isMouseTap = true; } } else if (isDown) { this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); } // update the down state of the tracking data if (trackingData) { if (isRightButton) { trackingData.rightDown = false; } else { trackingData.leftDown = false; } } } // Pointers and Touches, and Mouse if (hit) { this.dispatchEvent(displayObject, 'pointerup', interactionEvent); if (isTouch) { this.dispatchEvent(displayObject, 'touchend', interactionEvent); } if (trackingData) { // emit pointertap if not a mouse, or if the mouse block decided it was a tap if (!isMouse || isMouseTap) { this.dispatchEvent(displayObject, 'pointertap', interactionEvent); } if (isTouch) { this.dispatchEvent(displayObject, 'tap', interactionEvent); // touches are no longer over (if they ever were) when we get the touchend // so we should ensure that we don't keep pretending that they are trackingData.over = false; } } } else if (trackingData) { this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); if (isTouch) { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); } } // Only remove the tracking data if there is no over/down state still associated with it if (trackingData && trackingData.none) { delete displayObject.trackedPointers[id]; } }; /** * Is called when the pointer moves across the renderer element * * @private * @param {PointerEvent} originalEvent - The DOM event of a pointer moving */ InteractionManager.prototype.onPointerMove = function onPointerMove (originalEvent) { // if we support touch events, then only use those for touch events, not pointer events if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') { return; } var events = this.normalizeToPointerData(originalEvent); if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { this.didMove = true; this.cursor = null; } var eventLen = events.length; for (var i = 0; i < eventLen; i++) { var event = events[i]; var interactionData = this.getInteractionDataForPointerId(event); var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); interactionEvent.data.originalEvent = originalEvent; this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, true); this.emit('pointermove', interactionEvent); if (event.pointerType === 'touch') { this.emit('touchmove', interactionEvent); } if (event.pointerType === 'mouse' || event.pointerType === 'pen') { this.emit('mousemove', interactionEvent); } } if (events[0].pointerType === 'mouse') { this.setCursorMode(this.cursor); // TODO BUG for parents interactive object (border order issue) } }; /** * Processes the result of the pointer move check and dispatches the event if need be * * @private * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */ InteractionManager.prototype.processPointerMove = function processPointerMove (interactionEvent, displayObject, hit) { var data = interactionEvent.data; var isTouch = data.pointerType === 'touch'; var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); if (isMouse) { this.processPointerOverOut(interactionEvent, displayObject, hit); } if (!this.moveWhenInside || hit) { this.dispatchEvent(displayObject, 'pointermove', interactionEvent); if (isTouch) { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); } if (isMouse) { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); } } }; /** * Is called when the pointer is moved out of the renderer element * * @private * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out */ InteractionManager.prototype.onPointerOut = function onPointerOut (originalEvent) { // if we support touch events, then only use those for touch events, not pointer events if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') { return; } var events = this.normalizeToPointerData(originalEvent); // Only mouse and pointer can call onPointerOut, so events will always be length 1 var event = events[0]; if (event.pointerType === 'mouse') { this.mouseOverRenderer = false; this.setCursorMode(null); } var interactionData = this.getInteractionDataForPointerId(event); var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); interactionEvent.data.originalEvent = event; this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); this.emit('pointerout', interactionEvent); if (event.pointerType === 'mouse' || event.pointerType === 'pen') { this.emit('mouseout', interactionEvent); } else { // we can get touchleave events after touchend, so we want to make sure we don't // introduce memory leaks this.releaseInteractionDataForPointerId(interactionData.identifier); } }; /** * Processes the result of the pointer over/out check and dispatches the event if need be * * @private * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */ InteractionManager.prototype.processPointerOverOut = function processPointerOverOut (interactionEvent, displayObject, hit) { var data = interactionEvent.data; var id = interactionEvent.data.identifier; var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); var trackingData = displayObject.trackedPointers[id]; // if we just moused over the display object, then we need to track that state if (hit && !trackingData) { trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id); } if (trackingData === undefined) { return; } if (hit && this.mouseOverRenderer) { if (!trackingData.over) { trackingData.over = true; this.delayDispatchEvent(displayObject, 'pointerover', interactionEvent); if (isMouse) { this.delayDispatchEvent(displayObject, 'mouseover', interactionEvent); } } // only change the cursor if it has not already been changed (by something deeper in the // display tree) if (isMouse && this.cursor === null) { this.cursor = displayObject.cursor; } } else if (trackingData.over) { trackingData.over = false; this.dispatchEvent(displayObject, 'pointerout', this.eventData); if (isMouse) { this.dispatchEvent(displayObject, 'mouseout', interactionEvent); } // if there is no mouse down information for the pointer, then it is safe to delete if (trackingData.none) { delete displayObject.trackedPointers[id]; } } }; /** * Is called when the pointer is moved into the renderer element * * @private * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view */ InteractionManager.prototype.onPointerOver = function onPointerOver (originalEvent) { var events = this.normalizeToPointerData(originalEvent); // Only mouse and pointer can call onPointerOver, so events will always be length 1 var event = events[0]; var interactionData = this.getInteractionDataForPointerId(event); var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); interactionEvent.data.originalEvent = event; if (event.pointerType === 'mouse') { this.mouseOverRenderer = true; } this.emit('pointerover', interactionEvent); if (event.pointerType === 'mouse' || event.pointerType === 'pen') { this.emit('mouseover', interactionEvent); } }; /** * Get InteractionData for a given pointerId. Store that data as well * * @private * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier */ InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId (event) { var pointerId = event.pointerId; var interactionData; if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { interactionData = this.mouse; } else if (this.activeInteractionData[pointerId]) { interactionData = this.activeInteractionData[pointerId]; } else { interactionData = this.interactionDataPool.pop() || new InteractionData(); interactionData.identifier = pointerId; this.activeInteractionData[pointerId] = interactionData; } // copy properties from the event, so that we can make sure that touch/pointer specific // data is available interactionData.copyEvent(event); return interactionData; }; /** * Return unused InteractionData to the pool, for a given pointerId * * @private * @param {number} pointerId - Identifier from a pointer event */ InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId (pointerId) { var interactionData = this.activeInteractionData[pointerId]; if (interactionData) { delete this.activeInteractionData[pointerId]; interactionData.reset(); this.interactionDataPool.push(interactionData); } }; /** * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData * * @private * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired * with the InteractionEvent * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in */ InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent (interactionEvent, pointerEvent, interactionData) { interactionEvent.data = interactionData; this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); // Not really sure why this is happening, but it's how a previous version handled things if (pointerEvent.pointerType === 'touch') { pointerEvent.globalX = interactionData.global.x; pointerEvent.globalY = interactionData.global.y; } interactionData.originalEvent = pointerEvent; interactionEvent.reset(); return interactionEvent; }; /** * Ensures that the original event object contains all data that a regular pointer event would have * * @private * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer * or mouse event, or a multiple normalized pointer events if there are multiple changed touches */ InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData (event) { var normalizedEvents = []; if (this.supportsTouchEvents && event instanceof TouchEvent) { for (var i = 0, li = event.changedTouches.length; i < li; i++) { var touch = event.changedTouches[i]; if (typeof touch.button === 'undefined') { touch.button = event.touches.length ? 1 : 0; } if (typeof touch.buttons === 'undefined') { touch.buttons = event.touches.length ? 1 : 0; } if (typeof touch.isPrimary === 'undefined') { touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; } if (typeof touch.width === 'undefined') { touch.width = touch.radiusX || 1; } if (typeof touch.height === 'undefined') { touch.height = touch.radiusY || 1; } if (typeof touch.tiltX === 'undefined') { touch.tiltX = 0; } if (typeof touch.tiltY === 'undefined') { touch.tiltY = 0; } if (typeof touch.pointerType === 'undefined') { touch.pointerType = 'touch'; } if (typeof touch.pointerId === 'undefined') { touch.pointerId = touch.identifier || 0; } if (typeof touch.pressure === 'undefined') { touch.pressure = touch.force || 0.5; } if (typeof touch.twist === 'undefined') { touch.twist = 0; } if (typeof touch.tangentialPressure === 'undefined') { touch.tangentialPressure = 0; } // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven // support, and the fill ins are not quite the same // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top // left is not 0,0 on the page if (typeof touch.layerX === 'undefined') { touch.layerX = touch.offsetX = touch.clientX; } if (typeof touch.layerY === 'undefined') { touch.layerY = touch.offsetY = touch.clientY; } // mark the touch as normalized, just so that we know we did it touch.isNormalized = true; normalizedEvents.push(touch); } } // apparently PointerEvent subclasses MouseEvent, so yay else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { if (typeof event.isPrimary === 'undefined') { event.isPrimary = true; } if (typeof event.width === 'undefined') { event.width = 1; } if (typeof event.height === 'undefined') { event.height = 1; } if (typeof event.tiltX === 'undefined') { event.tiltX = 0; } if (typeof event.tiltY === 'undefined') { event.tiltY = 0; } if (typeof event.pointerType === 'undefined') { event.pointerType = 'mouse'; } if (typeof event.pointerId === 'undefined') { event.pointerId = MOUSE_POINTER_ID; } if (typeof event.pressure === 'undefined') { event.pressure = 0.5; } if (typeof event.twist === 'undefined') { event.twist = 0; } if (typeof event.tangentialPressure === 'undefined') { event.tangentialPressure = 0; } // mark the mouse event as normalized, just so that we know we did it event.isNormalized = true; normalizedEvents.push(event); } else { normalizedEvents.push(event); } return normalizedEvents; }; /** * Destroys the interaction manager * */ InteractionManager.prototype.destroy = function destroy () { this.removeEvents(); this.removeTickerListener(); this.removeAllListeners(); this.renderer = null; this.mouse = null; this.eventData = null; this.interactionDOMElement = null; this.onPointerDown = null; this.processPointerDown = null; this.onPointerUp = null; this.processPointerUp = null; this.onPointerCancel = null; this.processPointerCancel = null; this.onPointerMove = null; this.processPointerMove = null; this.onPointerOut = null; this.processPointerOverOut = null; this.onPointerOver = null; this.search = null; }; Object.defineProperties( InteractionManager.prototype, prototypeAccessors ); return InteractionManager; }(utils.EventEmitter)); /** * This namespace contains a renderer plugin for handling mouse, pointer, and touch events. * * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. * @namespace PIXI.interaction */ exports.InteractionData = InteractionData; exports.InteractionEvent = InteractionEvent; exports.InteractionManager = InteractionManager; exports.InteractionTrackingData = InteractionTrackingData; exports.interactiveTarget = interactiveTarget; },{"@pixi/display":8,"@pixi/math":21,"@pixi/ticker":38,"@pixi/utils":39}],20:[function(require,module,exports){ /*! * @pixi/loaders - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/loaders is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var resourceLoader = require('resource-loader'); var utils = require('@pixi/utils'); var core = require('@pixi/core'); /** * Loader plugin for handling Texture resources. * @class * @memberof PIXI * @implements PIXI.ILoaderPlugin */ var TextureLoader = function TextureLoader () {}; TextureLoader.use = function use (resource, next) { // create a new texture if the data is an Image object if (resource.data && resource.type === resourceLoader.Resource.TYPE.IMAGE) { resource.texture = core.Texture.fromLoader( resource.data, resource.url, resource.name ); } next(); }; /** * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader * * ```js * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use. * //or * const loader = new PIXI.Loader(); // you can also create your own if you want * * const sprites = {}; * * // Chainable `add` to enqueue a resource * loader.add('bunny', 'data/bunny.png') * .add('spaceship', 'assets/spritesheet.json'); * loader.add('scoreFont', 'assets/score.fnt'); * * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). * loader.pre(cachingMiddleware); * * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). * loader.use(parsingMiddleware); * * // The `load` method loads the queue of resources, and calls the passed in callback called once all * // resources have loaded. * loader.load((loader, resources) => { * // resources is an object where the key is the name of the resource loaded and the value is the resource object. * // They have a couple default properties: * // - `url`: The URL that the resource was loaded from * // - `error`: The error that happened when trying to load (if any) * // - `data`: The raw data that was loaded * // also may contain other properties based on the middleware that runs. * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); * }); * * // throughout the process multiple signals can be dispatched. * loader.onProgress.add(() => {}); // called once per loaded/errored file * loader.onError.add(() => {}); // called once per errored file * loader.onLoad.add(() => {}); // called once per loaded file * loader.onComplete.add(() => {}); // called once when the queued resources all load. * ``` * * @see https://github.com/englercj/resource-loader * * @class Loader * @memberof PIXI * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. * @param {number} [concurrency=10] - The number of resources to load concurrently. */ var Loader = /*@__PURE__*/(function (ResourceLoader) { function Loader(baseUrl, concurrency) { var this$1 = this; ResourceLoader.call(this, baseUrl, concurrency); utils.EventEmitter.call(this); for (var i = 0; i < Loader._plugins.length; ++i) { var plugin = Loader._plugins[i]; var pre = plugin.pre; var use = plugin.use; if (pre) { this.pre(pre); } if (use) { this.use(use); } } // Compat layer, translate the new v2 signals into old v1 events. this.onStart.add(function (l) { return this$1.emit('start', l); }); this.onProgress.add(function (l, r) { return this$1.emit('progress', l, r); }); this.onError.add(function (e, l, r) { return this$1.emit('error', e, l, r); }); this.onLoad.add(function (l, r) { return this$1.emit('load', l, r); }); this.onComplete.add(function (l, r) { return this$1.emit('complete', l, r); }); /** * If this loader cannot be destroyed. * @member {boolean} * @default false * @private */ this._protected = false; } if ( ResourceLoader ) Loader.__proto__ = ResourceLoader; Loader.prototype = Object.create( ResourceLoader && ResourceLoader.prototype ); Loader.prototype.constructor = Loader; var staticAccessors = { shared: { configurable: true } }; /** * Destroy the loader, removes references. * @private */ Loader.prototype.destroy = function destroy () { if (!this._protected) { this.removeAllListeners(); this.reset(); } }; /** * A premade instance of the loader that can be used to load resources. * @name shared * @type {PIXI.Loader} * @static * @memberof PIXI.Loader */ staticAccessors.shared.get = function () { var shared = Loader._shared; if (!shared) { shared = new Loader(); shared._protected = true; Loader._shared = shared; } return shared; }; Object.defineProperties( Loader, staticAccessors ); return Loader; }(resourceLoader.Loader)); // Copy EE3 prototype (mixin) Object.assign(Loader.prototype, utils.EventEmitter.prototype); /** * Collection of all installed `use` middleware for Loader. * * @static * @member {Array} _plugins * @memberof PIXI.Loader * @private */ Loader._plugins = []; /** * Adds a Loader plugin for the global shared loader and all * new Loader instances created. * * @static * @method registerPlugin * @memberof PIXI.Loader * @param {PIXI.ILoaderPlugin} plugin - The plugin to add * @return {PIXI.Loader} Reference to PIXI.Loader for chaining */ Loader.registerPlugin = function registerPlugin(plugin) { Loader._plugins.push(plugin); if (plugin.add) { plugin.add(); } return Loader; }; // parse any blob into more usable objects (e.g. Image) Loader.registerPlugin({ use: resourceLoader.middleware.parsing }); // parse any Image objects into textures Loader.registerPlugin(TextureLoader); /** * Plugin to be installed for handling specific Loader resources. * * @memberof PIXI * @typedef ILoaderPlugin * @property {function} [add] - Function to call immediate after registering plugin. * @property {PIXI.Loader.loaderMiddleware} [pre] - Middleware function to run before load, the * arguments for this are `(resource, next)` * @property {PIXI.Loader.loaderMiddleware} [use] - Middleware function to run after load, the * arguments for this are `(resource, next)` */ /** * @memberof PIXI.Loader * @callback loaderMiddleware * @param {PIXI.LoaderResource} resource * @param {function} next */ /** * @memberof PIXI.Loader# * @member {object} onStart */ /** * @memberof PIXI.Loader# * @member {object} onProgress */ /** * @memberof PIXI.Loader# * @member {object} onError */ /** * @memberof PIXI.Loader# * @member {object} onLoad */ /** * @memberof PIXI.Loader# * @member {object} onComplete */ /** * Application plugin for supporting loader option. Installing the LoaderPlugin * is not necessary if using **pixi.js** or **pixi.js-legacy**. * @example * import {AppLoaderPlugin} from '@pixi/loaders'; * import {Application} from '@pixi/app'; * Application.registerPlugin(AppLoaderPlugin); * @class * @memberof PIXI */ var AppLoaderPlugin = function AppLoaderPlugin () {}; AppLoaderPlugin.init = function init (options) { options = Object.assign({ sharedLoader: false, }, options); /** * Loader instance to help with asset loading. * @name PIXI.Application#loader * @type {PIXI.Loader} * @readonly */ this.loader = options.sharedLoader ? Loader.shared : new Loader(); }; /** * Called when application destroyed * @private */ AppLoaderPlugin.destroy = function destroy () { if (this.loader) { this.loader.destroy(); this.loader = null; } }; /** * Reference to **{@link https://github.com/englercj/resource-loader * resource-loader}**'s Resource class. * @see http://englercj.github.io/resource-loader/Resource.html * @class LoaderResource * @memberof PIXI */ var LoaderResource = resourceLoader.Resource; exports.AppLoaderPlugin = AppLoaderPlugin; exports.Loader = Loader; exports.LoaderResource = LoaderResource; exports.TextureLoader = TextureLoader; },{"@pixi/core":7,"@pixi/utils":39,"resource-loader":385}],21:[function(require,module,exports){ /*! * @pixi/math - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/math is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * Common interface for points. Both Point and ObservablePoint implement it * @memberof PIXI * @interface IPoint */ /** * X coord * @memberof PIXI.IPoint# * @member {number} x */ /** * Y coord * @memberof PIXI.IPoint# * @member {number} y */ /** * Sets the point to a new x and y position. * If y is omitted, both x and y will be set to x. * * @method set * @memberof PIXI.IPoint# * @param {number} [x=0] - position of the point on the x axis * @param {number} [y=x] - position of the point on the y axis */ /** * Copies x and y from the given point * @method copyFrom * @memberof PIXI.IPoint# * @param {PIXI.IPoint} p - The point to copy from * @returns {this} Returns itself. */ /** * Copies x and y into the given point * @method copyTo * @memberof PIXI.IPoint# * @param {PIXI.IPoint} p - The point to copy. * @returns {PIXI.IPoint} Given point with values updated */ /** * Returns true if the given point is equal to this point * * @method equals * @memberof PIXI.IPoint# * @param {PIXI.IPoint} p - The point to check * @returns {boolean} Whether the given point equal to this point */ /** * The Point object represents a location in a two-dimensional coordinate system, where x represents * the horizontal axis and y represents the vertical axis. * * @class * @memberof PIXI * @implements IPoint */ var Point = /** @class */ (function () { /** * @param {number} [x=0] - position of the point on the x axis * @param {number} [y=0] - position of the point on the y axis */ function Point(x, y) { if (x === void 0) { x = 0; } if (y === void 0) { y = 0; } /** * @member {number} * @default 0 */ this.x = x; /** * @member {number} * @default 0 */ this.y = y; } /** * Creates a clone of this point * * @return {PIXI.Point} a copy of the point */ Point.prototype.clone = function () { return new Point(this.x, this.y); }; /** * Copies x and y from the given point * * @param {PIXI.IPoint} p - The point to copy from * @returns {this} Returns itself. */ Point.prototype.copyFrom = function (p) { this.set(p.x, p.y); return this; }; /** * Copies x and y into the given point * * @param {PIXI.IPoint} p - The point to copy. * @returns {PIXI.IPoint} Given point with values updated */ Point.prototype.copyTo = function (p) { p.set(this.x, this.y); return p; }; /** * Returns true if the given point is equal to this point * * @param {PIXI.IPoint} p - The point to check * @returns {boolean} Whether the given point equal to this point */ Point.prototype.equals = function (p) { return (p.x === this.x) && (p.y === this.y); }; /** * Sets the point to a new x and y position. * If y is omitted, both x and y will be set to x. * * @param {number} [x=0] - position of the point on the x axis * @param {number} [y=x] - position of the point on the y axis * @returns {this} Returns itself. */ Point.prototype.set = function (x, y) { if (x === void 0) { x = 0; } if (y === void 0) { y = x; } this.x = x; this.y = y; return this; }; return Point; }()); /** * The Point object represents a location in a two-dimensional coordinate system, where x represents * the horizontal axis and y represents the vertical axis. * * An ObservablePoint is a point that triggers a callback when the point's position is changed. * * @class * @memberof PIXI * @implements IPoint */ var ObservablePoint = /** @class */ (function () { /** * @param {Function} cb - callback when changed * @param {object} scope - owner of callback * @param {number} [x=0] - position of the point on the x axis * @param {number} [y=0] - position of the point on the y axis */ function ObservablePoint(cb, scope, x, y) { if (x === void 0) { x = 0; } if (y === void 0) { y = 0; } this._x = x; this._y = y; this.cb = cb; this.scope = scope; } /** * Creates a clone of this point. * The callback and scope params can be overidden otherwise they will default * to the clone object's values. * * @override * @param {Function} [cb=null] - callback when changed * @param {object} [scope=null] - owner of callback * @return {PIXI.ObservablePoint} a copy of the point */ ObservablePoint.prototype.clone = function (cb, scope) { if (cb === void 0) { cb = this.cb; } if (scope === void 0) { scope = this.scope; } return new ObservablePoint(cb, scope, this._x, this._y); }; /** * Sets the point to a new x and y position. * If y is omitted, both x and y will be set to x. * * @param {number} [x=0] - position of the point on the x axis * @param {number} [y=x] - position of the point on the y axis * @returns {this} Returns itself. */ ObservablePoint.prototype.set = function (x, y) { if (x === void 0) { x = 0; } if (y === void 0) { y = x; } if (this._x !== x || this._y !== y) { this._x = x; this._y = y; this.cb.call(this.scope); } return this; }; /** * Copies x and y from the given point * * @param {PIXI.IPoint} p - The point to copy from. * @returns {this} Returns itself. */ ObservablePoint.prototype.copyFrom = function (p) { if (this._x !== p.x || this._y !== p.y) { this._x = p.x; this._y = p.y; this.cb.call(this.scope); } return this; }; /** * Copies x and y into the given point * * @param {PIXI.IPoint} p - The point to copy. * @returns {PIXI.IPoint} Given point with values updated */ ObservablePoint.prototype.copyTo = function (p) { p.set(this._x, this._y); return p; }; /** * Returns true if the given point is equal to this point * * @param {PIXI.IPoint} p - The point to check * @returns {boolean} Whether the given point equal to this point */ ObservablePoint.prototype.equals = function (p) { return (p.x === this._x) && (p.y === this._y); }; Object.defineProperty(ObservablePoint.prototype, "x", { /** * The position of the displayObject on the x axis relative to the local coordinates of the parent. * * @member {number} */ get: function () { return this._x; }, set: function (value) { if (this._x !== value) { this._x = value; this.cb.call(this.scope); } }, enumerable: true, configurable: true }); Object.defineProperty(ObservablePoint.prototype, "y", { /** * The position of the displayObject on the x axis relative to the local coordinates of the parent. * * @member {number} */ get: function () { return this._y; }, set: function (value) { if (this._y !== value) { this._y = value; this.cb.call(this.scope); } }, enumerable: true, configurable: true }); return ObservablePoint; }()); /** * Two Pi. * * @static * @constant {number} PI_2 * @memberof PIXI */ var PI_2 = Math.PI * 2; /** * Conversion factor for converting radians to degrees. * * @static * @constant {number} RAD_TO_DEG * @memberof PIXI */ var RAD_TO_DEG = 180 / Math.PI; /** * Conversion factor for converting degrees to radians. * * @static * @constant {number} DEG_TO_RAD * @memberof PIXI */ var DEG_TO_RAD = Math.PI / 180; (function (SHAPES) { SHAPES[SHAPES["POLY"] = 0] = "POLY"; SHAPES[SHAPES["RECT"] = 1] = "RECT"; SHAPES[SHAPES["CIRC"] = 2] = "CIRC"; SHAPES[SHAPES["ELIP"] = 3] = "ELIP"; SHAPES[SHAPES["RREC"] = 4] = "RREC"; })(exports.SHAPES || (exports.SHAPES = {})); /** * Constants that identify shapes, mainly to prevent `instanceof` calls. * * @static * @constant * @name SHAPES * @memberof PIXI * @type {enum} * @property {number} POLY Polygon * @property {number} RECT Rectangle * @property {number} CIRC Circle * @property {number} ELIP Ellipse * @property {number} RREC Rounded Rectangle * @enum {number} */ /** * The PixiJS Matrix as a class makes it a lot faster. * * Here is a representation of it: * ```js * | a | c | tx| * | b | d | ty| * | 0 | 0 | 1 | * ``` * @class * @memberof PIXI */ var Matrix = /** @class */ (function () { /** * @param {number} [a=1] - x scale * @param {number} [b=0] - x skew * @param {number} [c=0] - y skew * @param {number} [d=1] - y scale * @param {number} [tx=0] - x translation * @param {number} [ty=0] - y translation */ function Matrix(a, b, c, d, tx, ty) { if (a === void 0) { a = 1; } if (b === void 0) { b = 0; } if (c === void 0) { c = 0; } if (d === void 0) { d = 1; } if (tx === void 0) { tx = 0; } if (ty === void 0) { ty = 0; } this.array = null; /** * @member {number} * @default 1 */ this.a = a; /** * @member {number} * @default 0 */ this.b = b; /** * @member {number} * @default 0 */ this.c = c; /** * @member {number} * @default 1 */ this.d = d; /** * @member {number} * @default 0 */ this.tx = tx; /** * @member {number} * @default 0 */ this.ty = ty; } /** * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: * * a = array[0] * b = array[1] * c = array[3] * d = array[4] * tx = array[2] * ty = array[5] * * @param {number[]} array - The array that the matrix will be populated from. */ Matrix.prototype.fromArray = function (array) { this.a = array[0]; this.b = array[1]; this.c = array[3]; this.d = array[4]; this.tx = array[2]; this.ty = array[5]; }; /** * sets the matrix properties * * @param {number} a - Matrix component * @param {number} b - Matrix component * @param {number} c - Matrix component * @param {number} d - Matrix component * @param {number} tx - Matrix component * @param {number} ty - Matrix component * * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ Matrix.prototype.set = function (a, b, c, d, tx, ty) { this.a = a; this.b = b; this.c = c; this.d = d; this.tx = tx; this.ty = ty; return this; }; /** * Creates an array from the current Matrix object. * * @param {boolean} transpose - Whether we need to transpose the matrix or not * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out * @return {number[]} the newly created array which contains the matrix */ Matrix.prototype.toArray = function (transpose, out) { if (!this.array) { this.array = new Float32Array(9); } var array = out || this.array; if (transpose) { array[0] = this.a; array[1] = this.b; array[2] = 0; array[3] = this.c; array[4] = this.d; array[5] = 0; array[6] = this.tx; array[7] = this.ty; array[8] = 1; } else { array[0] = this.a; array[1] = this.c; array[2] = this.tx; array[3] = this.b; array[4] = this.d; array[5] = this.ty; array[6] = 0; array[7] = 0; array[8] = 1; } return array; }; /** * Get a new position with the current transformation applied. * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) * * @param {PIXI.Point} pos - The origin * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) * @return {PIXI.Point} The new point, transformed through this matrix */ Matrix.prototype.apply = function (pos, newPos) { newPos = newPos || new Point(); var x = pos.x; var y = pos.y; newPos.x = (this.a * x) + (this.c * y) + this.tx; newPos.y = (this.b * x) + (this.d * y) + this.ty; return newPos; }; /** * Get a new position with the inverse of the current transformation applied. * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) * * @param {PIXI.Point} pos - The origin * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) * @return {PIXI.Point} The new point, inverse-transformed through this matrix */ Matrix.prototype.applyInverse = function (pos, newPos) { newPos = newPos || new Point(); var id = 1 / ((this.a * this.d) + (this.c * -this.b)); var x = pos.x; var y = pos.y; newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id); newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id); return newPos; }; /** * Translates the matrix on the x and y. * * @param {number} x How much to translate x by * @param {number} y How much to translate y by * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ Matrix.prototype.translate = function (x, y) { this.tx += x; this.ty += y; return this; }; /** * Applies a scale transformation to the matrix. * * @param {number} x The amount to scale horizontally * @param {number} y The amount to scale vertically * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ Matrix.prototype.scale = function (x, y) { this.a *= x; this.d *= y; this.c *= x; this.b *= y; this.tx *= x; this.ty *= y; return this; }; /** * Applies a rotation transformation to the matrix. * * @param {number} angle - The angle in radians. * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ Matrix.prototype.rotate = function (angle) { var cos = Math.cos(angle); var sin = Math.sin(angle); var a1 = this.a; var c1 = this.c; var tx1 = this.tx; this.a = (a1 * cos) - (this.b * sin); this.b = (a1 * sin) + (this.b * cos); this.c = (c1 * cos) - (this.d * sin); this.d = (c1 * sin) + (this.d * cos); this.tx = (tx1 * cos) - (this.ty * sin); this.ty = (tx1 * sin) + (this.ty * cos); return this; }; /** * Appends the given Matrix to this Matrix. * * @param {PIXI.Matrix} matrix - The matrix to append. * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ Matrix.prototype.append = function (matrix) { var a1 = this.a; var b1 = this.b; var c1 = this.c; var d1 = this.d; this.a = (matrix.a * a1) + (matrix.b * c1); this.b = (matrix.a * b1) + (matrix.b * d1); this.c = (matrix.c * a1) + (matrix.d * c1); this.d = (matrix.c * b1) + (matrix.d * d1); this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx; this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty; return this; }; /** * Sets the matrix based on all the available properties * * @param {number} x - Position on the x axis * @param {number} y - Position on the y axis * @param {number} pivotX - Pivot on the x axis * @param {number} pivotY - Pivot on the y axis * @param {number} scaleX - Scale on the x axis * @param {number} scaleY - Scale on the y axis * @param {number} rotation - Rotation in radians * @param {number} skewX - Skew on the x axis * @param {number} skewY - Skew on the y axis * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { this.a = Math.cos(rotation + skewY) * scaleX; this.b = Math.sin(rotation + skewY) * scaleX; this.c = -Math.sin(rotation - skewX) * scaleY; this.d = Math.cos(rotation - skewX) * scaleY; this.tx = x - ((pivotX * this.a) + (pivotY * this.c)); this.ty = y - ((pivotX * this.b) + (pivotY * this.d)); return this; }; /** * Prepends the given Matrix to this Matrix. * * @param {PIXI.Matrix} matrix - The matrix to prepend * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ Matrix.prototype.prepend = function (matrix) { var tx1 = this.tx; if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { var a1 = this.a; var c1 = this.c; this.a = (a1 * matrix.a) + (this.b * matrix.c); this.b = (a1 * matrix.b) + (this.b * matrix.d); this.c = (c1 * matrix.a) + (this.d * matrix.c); this.d = (c1 * matrix.b) + (this.d * matrix.d); } this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx; this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty; return this; }; /** * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. * * @param {PIXI.Transform} transform - The transform to apply the properties to. * @return {PIXI.Transform} The transform with the newly applied properties */ Matrix.prototype.decompose = function (transform) { // sort out rotation / skew.. var a = this.a; var b = this.b; var c = this.c; var d = this.d; var skewX = -Math.atan2(-c, d); var skewY = Math.atan2(b, a); var delta = Math.abs(skewX + skewY); if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) { transform.rotation = skewY; transform.skew.x = transform.skew.y = 0; } else { transform.rotation = 0; transform.skew.x = skewX; transform.skew.y = skewY; } // next set scale transform.scale.x = Math.sqrt((a * a) + (b * b)); transform.scale.y = Math.sqrt((c * c) + (d * d)); // next set position transform.position.x = this.tx; transform.position.y = this.ty; return transform; }; /** * Inverts this matrix * * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ Matrix.prototype.invert = function () { var a1 = this.a; var b1 = this.b; var c1 = this.c; var d1 = this.d; var tx1 = this.tx; var n = (a1 * d1) - (b1 * c1); this.a = d1 / n; this.b = -b1 / n; this.c = -c1 / n; this.d = a1 / n; this.tx = ((c1 * this.ty) - (d1 * tx1)) / n; this.ty = -((a1 * this.ty) - (b1 * tx1)) / n; return this; }; /** * Resets this Matrix to an identity (default) matrix. * * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ Matrix.prototype.identity = function () { this.a = 1; this.b = 0; this.c = 0; this.d = 1; this.tx = 0; this.ty = 0; return this; }; /** * Creates a new Matrix object with the same values as this one. * * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. */ Matrix.prototype.clone = function () { var matrix = new Matrix(); matrix.a = this.a; matrix.b = this.b; matrix.c = this.c; matrix.d = this.d; matrix.tx = this.tx; matrix.ty = this.ty; return matrix; }; /** * Changes the values of the given matrix to be the same as the ones in this matrix * * @param {PIXI.Matrix} matrix - The matrix to copy to. * @return {PIXI.Matrix} The matrix given in parameter with its values updated. */ Matrix.prototype.copyTo = function (matrix) { matrix.a = this.a; matrix.b = this.b; matrix.c = this.c; matrix.d = this.d; matrix.tx = this.tx; matrix.ty = this.ty; return matrix; }; /** * Changes the values of the matrix to be the same as the ones in given matrix * * @param {PIXI.Matrix} matrix - The matrix to copy from. * @return {PIXI.Matrix} this */ Matrix.prototype.copyFrom = function (matrix) { this.a = matrix.a; this.b = matrix.b; this.c = matrix.c; this.d = matrix.d; this.tx = matrix.tx; this.ty = matrix.ty; return this; }; Object.defineProperty(Matrix, "IDENTITY", { /** * A default (identity) matrix * * @static * @const * @member {PIXI.Matrix} */ get: function () { return new Matrix(); }, enumerable: true, configurable: true }); Object.defineProperty(Matrix, "TEMP_MATRIX", { /** * A temp matrix * * @static * @const * @member {PIXI.Matrix} */ get: function () { return new Matrix(); }, enumerable: true, configurable: true }); return Matrix; }()); // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group /* * Transform matrix for operation n is: * | ux | vx | * | uy | vy | */ var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; /** * [Cayley Table]{@link https://en.wikipedia.org/wiki/Cayley_table} * for the composition of each rotation in the dihederal group D8. * * @type number[][] * @private */ var rotationCayley = []; /** * Matrices for each `GD8Symmetry` rotation. * * @type Matrix[] * @private */ var rotationMatrices = []; /* * Alias for {@code Math.sign}. */ var signum = Math.sign; /* * Initializes `rotationCayley` and `rotationMatrices`. It is called * only once below. */ function init() { for (var i = 0; i < 16; i++) { var row = []; rotationCayley.push(row); for (var j = 0; j < 16; j++) { /* Multiplies rotation matrices i and j. */ var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j])); var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j])); var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j])); var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j])); /* Finds rotation matrix matching the product and pushes it. */ for (var k = 0; k < 16; k++) { if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { row.push(k); break; } } } } for (var i = 0; i < 16; i++) { var mat = new Matrix(); mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); rotationMatrices.push(mat); } } init(); /** * @memberof PIXI * @typedef {number} GD8Symmetry * @see PIXI.groupD8 */ /** * Implements the dihedral group D8, which is similar to * [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}; * D8 is the same but with diagonals, and it is used for texture * rotations. * * The directions the U- and V- axes after rotation * of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))` * and `(vX(a), vY(a))`. These aren't necessarily unit vectors. * * **Origin:**
* This is the small part of gameofbombs.com portal system. It works. * * @see PIXI.groupD8.E * @see PIXI.groupD8.SE * @see PIXI.groupD8.S * @see PIXI.groupD8.SW * @see PIXI.groupD8.W * @see PIXI.groupD8.NW * @see PIXI.groupD8.N * @see PIXI.groupD8.NE * @author Ivan @ivanpopelyshev * @namespace PIXI.groupD8 * @memberof PIXI */ var groupD8 = { /** * | Rotation | Direction | * |----------|-----------| * | 0° | East | * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ E: 0, /** * | Rotation | Direction | * |----------|-----------| * | 45°↻ | Southeast | * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ SE: 1, /** * | Rotation | Direction | * |----------|-----------| * | 90°↻ | South | * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ S: 2, /** * | Rotation | Direction | * |----------|-----------| * | 135°↻ | Southwest | * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ SW: 3, /** * | Rotation | Direction | * |----------|-----------| * | 180° | West | * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ W: 4, /** * | Rotation | Direction | * |-------------|--------------| * | -135°/225°↻ | Northwest | * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ NW: 5, /** * | Rotation | Direction | * |-------------|--------------| * | -90°/270°↻ | North | * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ N: 6, /** * | Rotation | Direction | * |-------------|--------------| * | -45°/315°↻ | Northeast | * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ NE: 7, /** * Reflection about Y-axis. * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ MIRROR_VERTICAL: 8, /** * Reflection about the main diagonal. * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ MAIN_DIAGONAL: 10, /** * Reflection about X-axis. * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ MIRROR_HORIZONTAL: 12, /** * Reflection about reverse diagonal. * * @memberof PIXI.groupD8 * @constant {PIXI.GD8Symmetry} */ REVERSE_DIAGONAL: 14, /** * @memberof PIXI.groupD8 * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. * @return {PIXI.GD8Symmetry} The X-component of the U-axis * after rotating the axes. */ uX: function (ind) { return ux[ind]; }, /** * @memberof PIXI.groupD8 * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. * @return {PIXI.GD8Symmetry} The Y-component of the U-axis * after rotating the axes. */ uY: function (ind) { return uy[ind]; }, /** * @memberof PIXI.groupD8 * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. * @return {PIXI.GD8Symmetry} The X-component of the V-axis * after rotating the axes. */ vX: function (ind) { return vx[ind]; }, /** * @memberof PIXI.groupD8 * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. * @return {PIXI.GD8Symmetry} The Y-component of the V-axis * after rotating the axes. */ vY: function (ind) { return vy[ind]; }, /** * @memberof PIXI.groupD8 * @param {PIXI.GD8Symmetry} rotation - symmetry whose opposite * is needed. Only rotations have opposite symmetries while * reflections don't. * @return {PIXI.GD8Symmetry} The opposite symmetry of `rotation` */ inv: function (rotation) { if (rotation & 8) // true only if between 8 & 15 (reflections) { return rotation & 15; // or rotation % 16 } return (-rotation) & 7; // or (8 - rotation) % 8 }, /** * Composes the two D8 operations. * * Taking `^` as reflection: * * | | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 | * |-------|-----|-----|-----|-----|------|-------|-------|-------| * | E=0 | E | S | W | N | E^ | S^ | W^ | N^ | * | S=2 | S | W | N | E | S^ | W^ | N^ | E^ | * | W=4 | W | N | E | S | W^ | N^ | E^ | S^ | * | N=6 | N | E | S | W | N^ | E^ | S^ | W^ | * | E^=8 | E^ | N^ | W^ | S^ | E | N | W | S | * | S^=10 | S^ | E^ | N^ | W^ | S | E | N | W | * | W^=12 | W^ | S^ | E^ | N^ | W | S | E | N | * | N^=14 | N^ | W^ | S^ | E^ | N | W | S | E | * * [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table} * @memberof PIXI.groupD8 * @param {PIXI.GD8Symmetry} rotationSecond - Second operation, which * is the row in the above cayley table. * @param {PIXI.GD8Symmetry} rotationFirst - First operation, which * is the column in the above cayley table. * @return {PIXI.GD8Symmetry} Composed operation */ add: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][rotationFirst]); }, /** * Reverse of `add`. * * @memberof PIXI.groupD8 * @param {PIXI.GD8Symmetry} rotationSecond - Second operation * @param {PIXI.GD8Symmetry} rotationFirst - First operation * @return {PIXI.GD8Symmetry} Result */ sub: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][groupD8.inv(rotationFirst)]); }, /** * Adds 180 degrees to rotation, which is a commutative * operation. * * @memberof PIXI.groupD8 * @param {number} rotation - The number to rotate. * @returns {number} Rotated number */ rotate180: function (rotation) { return rotation ^ 4; }, /** * Checks if the rotation angle is vertical, i.e. south * or north. It doesn't work for reflections. * * @memberof PIXI.groupD8 * @param {PIXI.GD8Symmetry} rotation - The number to check. * @returns {boolean} Whether or not the direction is vertical */ isVertical: function (rotation) { return (rotation & 3) === 2; }, /** * Approximates the vector `V(dx,dy)` into one of the * eight directions provided by `groupD8`. * * @memberof PIXI.groupD8 * @param {number} dx - X-component of the vector * @param {number} dy - Y-component of the vector * @return {PIXI.GD8Symmetry} Approximation of the vector into * one of the eight symmetries. */ byDirection: function (dx, dy) { if (Math.abs(dx) * 2 <= Math.abs(dy)) { if (dy >= 0) { return groupD8.S; } return groupD8.N; } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { if (dx > 0) { return groupD8.E; } return groupD8.W; } else if (dy > 0) { if (dx > 0) { return groupD8.SE; } return groupD8.SW; } else if (dx > 0) { return groupD8.NE; } return groupD8.NW; }, /** * Helps sprite to compensate texture packer rotation. * * @memberof PIXI.groupD8 * @param {PIXI.Matrix} matrix - sprite world matrix * @param {PIXI.GD8Symmetry} rotation - The rotation factor to use. * @param {number} tx - sprite anchoring * @param {number} ty - sprite anchoring */ matrixAppendRotationInv: function (matrix, rotation, tx, ty) { if (tx === void 0) { tx = 0; } if (ty === void 0) { ty = 0; } // Packer used "rotation", we use "inv(rotation)" var mat = rotationMatrices[groupD8.inv(rotation)]; mat.tx = tx; mat.ty = ty; matrix.append(mat); }, }; /** * Transform that takes care about its versions * * @class * @memberof PIXI */ var Transform = /** @class */ (function () { function Transform() { /** * The world transformation matrix. * * @member {PIXI.Matrix} */ this.worldTransform = new Matrix(); /** * The local transformation matrix. * * @member {PIXI.Matrix} */ this.localTransform = new Matrix(); /** * The coordinate of the object relative to the local coordinates of the parent. * * @member {PIXI.ObservablePoint} */ this.position = new ObservablePoint(this.onChange, this, 0, 0); /** * The scale factor of the object. * * @member {PIXI.ObservablePoint} */ this.scale = new ObservablePoint(this.onChange, this, 1, 1); /** * The pivot point of the displayObject that it rotates around. * * @member {PIXI.ObservablePoint} */ this.pivot = new ObservablePoint(this.onChange, this, 0, 0); /** * The skew amount, on the x and y axis. * * @member {PIXI.ObservablePoint} */ this.skew = new ObservablePoint(this.updateSkew, this, 0, 0); /** * The rotation amount. * * @protected * @member {number} */ this._rotation = 0; /** * The X-coordinate value of the normalized local X axis, * the first column of the local transformation matrix without a scale. * * @protected * @member {number} */ this._cx = 1; /** * The Y-coordinate value of the normalized local X axis, * the first column of the local transformation matrix without a scale. * * @protected * @member {number} */ this._sx = 0; /** * The X-coordinate value of the normalized local Y axis, * the second column of the local transformation matrix without a scale. * * @protected * @member {number} */ this._cy = 0; /** * The Y-coordinate value of the normalized local Y axis, * the second column of the local transformation matrix without a scale. * * @protected * @member {number} */ this._sy = 1; /** * The locally unique ID of the local transform. * * @protected * @member {number} */ this._localID = 0; /** * The locally unique ID of the local transform * used to calculate the current local transformation matrix. * * @protected * @member {number} */ this._currentLocalID = 0; /** * The locally unique ID of the world transform. * * @protected * @member {number} */ this._worldID = 0; /** * The locally unique ID of the parent's world transform * used to calculate the current world transformation matrix. * * @protected * @member {number} */ this._parentID = 0; } /** * Called when a value changes. * * @protected */ Transform.prototype.onChange = function () { this._localID++; }; /** * Called when the skew or the rotation changes. * * @protected */ Transform.prototype.updateSkew = function () { this._cx = Math.cos(this._rotation + this.skew.y); this._sx = Math.sin(this._rotation + this.skew.y); this._cy = -Math.sin(this._rotation - this.skew.x); // cos, added PI/2 this._sy = Math.cos(this._rotation - this.skew.x); // sin, added PI/2 this._localID++; }; /** * Updates the local transformation matrix. */ Transform.prototype.updateLocalTransform = function () { var lt = this.localTransform; if (this._localID !== this._currentLocalID) { // get the matrix values of the displayobject based on its transform properties.. lt.a = this._cx * this.scale.x; lt.b = this._sx * this.scale.x; lt.c = this._cy * this.scale.y; lt.d = this._sy * this.scale.y; lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); this._currentLocalID = this._localID; // force an update.. this._parentID = -1; } }; /** * Updates the local and the world transformation matrices. * * @param {PIXI.Transform} parentTransform - The parent transform */ Transform.prototype.updateTransform = function (parentTransform) { var lt = this.localTransform; if (this._localID !== this._currentLocalID) { // get the matrix values of the displayobject based on its transform properties.. lt.a = this._cx * this.scale.x; lt.b = this._sx * this.scale.x; lt.c = this._cy * this.scale.y; lt.d = this._sy * this.scale.y; lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); this._currentLocalID = this._localID; // force an update.. this._parentID = -1; } if (this._parentID !== parentTransform._worldID) { // concat the parent matrix with the objects transform. var pt = parentTransform.worldTransform; var wt = this.worldTransform; wt.a = (lt.a * pt.a) + (lt.b * pt.c); wt.b = (lt.a * pt.b) + (lt.b * pt.d); wt.c = (lt.c * pt.a) + (lt.d * pt.c); wt.d = (lt.c * pt.b) + (lt.d * pt.d); wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx; wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty; this._parentID = parentTransform._worldID; // update the id of the transform.. this._worldID++; } }; /** * Decomposes a matrix and sets the transforms properties based on it. * * @param {PIXI.Matrix} matrix - The matrix to decompose */ Transform.prototype.setFromMatrix = function (matrix) { matrix.decompose(this); this._localID++; }; Object.defineProperty(Transform.prototype, "rotation", { /** * The rotation of the object in radians. * * @member {number} */ get: function () { return this._rotation; }, set: function (value) { if (this._rotation !== value) { this._rotation = value; this.updateSkew(); } }, enumerable: true, configurable: true }); /** * A default (identity) transform * * @static * @constant * @member {PIXI.Transform} */ Transform.IDENTITY = new Transform(); return Transform; }()); /** * Size object, contains width and height * * @memberof PIXI * @typedef {object} ISize * @property {number} width - Width component * @property {number} height - Height component */ /** * Rectangle object is an area defined by its position, as indicated by its top-left corner * point (x, y) and by its width and its height. * * @class * @memberof PIXI */ var Rectangle = /** @class */ (function () { /** * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle * @param {number} [width=0] - The overall width of this rectangle * @param {number} [height=0] - The overall height of this rectangle */ function Rectangle(x, y, width, height) { if (x === void 0) { x = 0; } if (y === void 0) { y = 0; } if (width === void 0) { width = 0; } if (height === void 0) { height = 0; } /** * @member {number} * @default 0 */ this.x = Number(x); /** * @member {number} * @default 0 */ this.y = Number(y); /** * @member {number} * @default 0 */ this.width = Number(width); /** * @member {number} * @default 0 */ this.height = Number(height); /** * The type of the object, mainly used to avoid `instanceof` checks * * @member {number} * @readOnly * @default PIXI.SHAPES.RECT * @see PIXI.SHAPES */ this.type = exports.SHAPES.RECT; } Object.defineProperty(Rectangle.prototype, "left", { /** * returns the left edge of the rectangle * * @member {number} */ get: function () { return this.x; }, enumerable: true, configurable: true }); Object.defineProperty(Rectangle.prototype, "right", { /** * returns the right edge of the rectangle * * @member {number} */ get: function () { return this.x + this.width; }, enumerable: true, configurable: true }); Object.defineProperty(Rectangle.prototype, "top", { /** * returns the top edge of the rectangle * * @member {number} */ get: function () { return this.y; }, enumerable: true, configurable: true }); Object.defineProperty(Rectangle.prototype, "bottom", { /** * returns the bottom edge of the rectangle * * @member {number} */ get: function () { return this.y + this.height; }, enumerable: true, configurable: true }); Object.defineProperty(Rectangle, "EMPTY", { /** * A constant empty rectangle. * * @static * @constant * @member {PIXI.Rectangle} * @return {PIXI.Rectangle} An empty rectangle */ get: function () { return new Rectangle(0, 0, 0, 0); }, enumerable: true, configurable: true }); /** * Creates a clone of this Rectangle * * @return {PIXI.Rectangle} a copy of the rectangle */ Rectangle.prototype.clone = function () { return new Rectangle(this.x, this.y, this.width, this.height); }; /** * Copies another rectangle to this one. * * @param {PIXI.Rectangle} rectangle - The rectangle to copy from. * @return {PIXI.Rectangle} Returns itself. */ Rectangle.prototype.copyFrom = function (rectangle) { this.x = rectangle.x; this.y = rectangle.y; this.width = rectangle.width; this.height = rectangle.height; return this; }; /** * Copies this rectangle to another one. * * @param {PIXI.Rectangle} rectangle - The rectangle to copy to. * @return {PIXI.Rectangle} Returns given parameter. */ Rectangle.prototype.copyTo = function (rectangle) { rectangle.x = this.x; rectangle.y = this.y; rectangle.width = this.width; rectangle.height = this.height; return rectangle; }; /** * Checks whether the x and y coordinates given are contained within this Rectangle * * @param {number} x - The X coordinate of the point to test * @param {number} y - The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ Rectangle.prototype.contains = function (x, y) { if (this.width <= 0 || this.height <= 0) { return false; } if (x >= this.x && x < this.x + this.width) { if (y >= this.y && y < this.y + this.height) { return true; } } return false; }; /** * Pads the rectangle making it grow in all directions. * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. * * @param {number} [paddingX=0] - The horizontal padding amount. * @param {number} [paddingY=0] - The vertical padding amount. * @return {PIXI.Rectangle} Returns itself. */ Rectangle.prototype.pad = function (paddingX, paddingY) { if (paddingX === void 0) { paddingX = 0; } if (paddingY === void 0) { paddingY = paddingX; } this.x -= paddingX; this.y -= paddingY; this.width += paddingX * 2; this.height += paddingY * 2; return this; }; /** * Fits this rectangle around the passed one. * * @param {PIXI.Rectangle} rectangle - The rectangle to fit. * @return {PIXI.Rectangle} Returns itself. */ Rectangle.prototype.fit = function (rectangle) { var x1 = Math.max(this.x, rectangle.x); var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width); var y1 = Math.max(this.y, rectangle.y); var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height); this.x = x1; this.width = Math.max(x2 - x1, 0); this.y = y1; this.height = Math.max(y2 - y1, 0); return this; }; /** * Enlarges rectangle that way its corners lie on grid * * @param {number} [resolution=1] resolution * @param {number} [eps=0.001] precision * @return {PIXI.Rectangle} Returns itself. */ Rectangle.prototype.ceil = function (resolution, eps) { if (resolution === void 0) { resolution = 1; } if (eps === void 0) { eps = 0.001; } var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution; var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution; this.x = Math.floor((this.x + eps) * resolution) / resolution; this.y = Math.floor((this.y + eps) * resolution) / resolution; this.width = x2 - this.x; this.height = y2 - this.y; return this; }; /** * Enlarges this rectangle to include the passed rectangle. * * @param {PIXI.Rectangle} rectangle - The rectangle to include. * @return {PIXI.Rectangle} Returns itself. */ Rectangle.prototype.enlarge = function (rectangle) { var x1 = Math.min(this.x, rectangle.x); var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); var y1 = Math.min(this.y, rectangle.y); var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); this.x = x1; this.width = x2 - x1; this.y = y1; this.height = y2 - y1; return this; }; return Rectangle; }()); /** * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects. * * @class * @memberof PIXI */ var Circle = /** @class */ (function () { /** * @param {number} [x=0] - The X coordinate of the center of this circle * @param {number} [y=0] - The Y coordinate of the center of this circle * @param {number} [radius=0] - The radius of the circle */ function Circle(x, y, radius) { if (x === void 0) { x = 0; } if (y === void 0) { y = 0; } if (radius === void 0) { radius = 0; } /** * @member {number} * @default 0 */ this.x = x; /** * @member {number} * @default 0 */ this.y = y; /** * @member {number} * @default 0 */ this.radius = radius; /** * The type of the object, mainly used to avoid `instanceof` checks * * @member {number} * @readOnly * @default PIXI.SHAPES.CIRC * @see PIXI.SHAPES */ this.type = exports.SHAPES.CIRC; } /** * Creates a clone of this Circle instance * * @return {PIXI.Circle} a copy of the Circle */ Circle.prototype.clone = function () { return new Circle(this.x, this.y, this.radius); }; /** * Checks whether the x and y coordinates given are contained within this circle * * @param {number} x - The X coordinate of the point to test * @param {number} y - The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ Circle.prototype.contains = function (x, y) { if (this.radius <= 0) { return false; } var r2 = this.radius * this.radius; var dx = (this.x - x); var dy = (this.y - y); dx *= dx; dy *= dy; return (dx + dy <= r2); }; /** * Returns the framing rectangle of the circle as a Rectangle object * * @return {PIXI.Rectangle} the framing rectangle */ Circle.prototype.getBounds = function () { return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; return Circle; }()); /** * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects. * * @class * @memberof PIXI */ var Ellipse = /** @class */ (function () { /** * @param {number} [x=0] - The X coordinate of the center of this ellipse * @param {number} [y=0] - The Y coordinate of the center of this ellipse * @param {number} [halfWidth=0] - The half width of this ellipse * @param {number} [halfHeight=0] - The half height of this ellipse */ function Ellipse(x, y, halfWidth, halfHeight) { if (x === void 0) { x = 0; } if (y === void 0) { y = 0; } if (halfWidth === void 0) { halfWidth = 0; } if (halfHeight === void 0) { halfHeight = 0; } /** * @member {number} * @default 0 */ this.x = x; /** * @member {number} * @default 0 */ this.y = y; /** * @member {number} * @default 0 */ this.width = halfWidth; /** * @member {number} * @default 0 */ this.height = halfHeight; /** * The type of the object, mainly used to avoid `instanceof` checks * * @member {number} * @readOnly * @default PIXI.SHAPES.ELIP * @see PIXI.SHAPES */ this.type = exports.SHAPES.ELIP; } /** * Creates a clone of this Ellipse instance * * @return {PIXI.Ellipse} a copy of the ellipse */ Ellipse.prototype.clone = function () { return new Ellipse(this.x, this.y, this.width, this.height); }; /** * Checks whether the x and y coordinates given are contained within this ellipse * * @param {number} x - The X coordinate of the point to test * @param {number} y - The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ Ellipse.prototype.contains = function (x, y) { if (this.width <= 0 || this.height <= 0) { return false; } // normalize the coords to an ellipse with center 0,0 var normx = ((x - this.x) / this.width); var normy = ((y - this.y) / this.height); normx *= normx; normy *= normy; return (normx + normy <= 1); }; /** * Returns the framing rectangle of the ellipse as a Rectangle object * * @return {PIXI.Rectangle} the framing rectangle */ Ellipse.prototype.getBounds = function () { return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; return Ellipse; }()); /** * A class to define a shape via user defined co-orinates. * * @class * @memberof PIXI */ var Polygon = /** @class */ (function () { /** * @param {PIXI.Point[]|number[]|number[][]} points - This can be an array of Points * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or * the arguments passed can be all the points of the polygon e.g. * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. */ function Polygon() { var arguments$1 = arguments; var points = []; for (var _i = 0; _i < arguments.length; _i++) { points[_i] = arguments$1[_i]; } if (Array.isArray(points[0])) { points = points[0]; } // if this is an array of points, convert it to a flat array of numbers if (points[0] instanceof Point) { points = points; var p = []; for (var i = 0, il = points.length; i < il; i++) { p.push(points[i].x, points[i].y); } points = p; } /** * An array of the points of this polygon * * @member {number[]} */ this.points = points; /** * The type of the object, mainly used to avoid `instanceof` checks * * @member {number} * @readOnly * @default PIXI.SHAPES.POLY * @see PIXI.SHAPES */ this.type = exports.SHAPES.POLY; /** * `false` after moveTo, `true` after `closePath`. In all other cases it is `true`. * @member {boolean} * @default true */ this.closeStroke = true; } /** * Creates a clone of this polygon * * @return {PIXI.Polygon} a copy of the polygon */ Polygon.prototype.clone = function () { var points = this.points.slice(); var polygon = new Polygon(points); polygon.closeStroke = this.closeStroke; return polygon; }; /** * Checks whether the x and y coordinates passed to this function are contained within this polygon * * @param {number} x - The X coordinate of the point to test * @param {number} y - The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ Polygon.prototype.contains = function (x, y) { var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; for (var i = 0, j = length - 1; i < length; j = i++) { var xi = this.points[i * 2]; var yi = this.points[(i * 2) + 1]; var xj = this.points[j * 2]; var yj = this.points[(j * 2) + 1]; var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi); if (intersect) { inside = !inside; } } return inside; }; return Polygon; }()); /** * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its * top-left corner point (x, y) and by its width and its height and its radius. * * @class * @memberof PIXI */ var RoundedRectangle = /** @class */ (function () { /** * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle * @param {number} [width=0] - The overall width of this rounded rectangle * @param {number} [height=0] - The overall height of this rounded rectangle * @param {number} [radius=20] - Controls the radius of the rounded corners */ function RoundedRectangle(x, y, width, height, radius) { if (x === void 0) { x = 0; } if (y === void 0) { y = 0; } if (width === void 0) { width = 0; } if (height === void 0) { height = 0; } if (radius === void 0) { radius = 20; } /** * @member {number} * @default 0 */ this.x = x; /** * @member {number} * @default 0 */ this.y = y; /** * @member {number} * @default 0 */ this.width = width; /** * @member {number} * @default 0 */ this.height = height; /** * @member {number} * @default 20 */ this.radius = radius; /** * The type of the object, mainly used to avoid `instanceof` checks * * @member {number} * @readonly * @default PIXI.SHAPES.RREC * @see PIXI.SHAPES */ this.type = exports.SHAPES.RREC; } /** * Creates a clone of this Rounded Rectangle * * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle */ RoundedRectangle.prototype.clone = function () { return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; /** * Checks whether the x and y coordinates given are contained within this Rounded Rectangle * * @param {number} x - The X coordinate of the point to test * @param {number} y - The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ RoundedRectangle.prototype.contains = function (x, y) { if (this.width <= 0 || this.height <= 0) { return false; } if (x >= this.x && x <= this.x + this.width) { if (y >= this.y && y <= this.y + this.height) { if ((y >= this.y + this.radius && y <= this.y + this.height - this.radius) || (x >= this.x + this.radius && x <= this.x + this.width - this.radius)) { return true; } var dx = x - (this.x + this.radius); var dy = y - (this.y + this.radius); var radius2 = this.radius * this.radius; if ((dx * dx) + (dy * dy) <= radius2) { return true; } dx = x - (this.x + this.width - this.radius); if ((dx * dx) + (dy * dy) <= radius2) { return true; } dy = y - (this.y + this.height - this.radius); if ((dx * dx) + (dy * dy) <= radius2) { return true; } dx = x - (this.x + this.radius); if ((dx * dx) + (dy * dy) <= radius2) { return true; } } } return false; }; return RoundedRectangle; }()); /** * Math classes and utilities mixed into PIXI namespace. * * @lends PIXI */ exports.Circle = Circle; exports.DEG_TO_RAD = DEG_TO_RAD; exports.Ellipse = Ellipse; exports.Matrix = Matrix; exports.ObservablePoint = ObservablePoint; exports.PI_2 = PI_2; exports.Point = Point; exports.Polygon = Polygon; exports.RAD_TO_DEG = RAD_TO_DEG; exports.Rectangle = Rectangle; exports.RoundedRectangle = RoundedRectangle; exports.Transform = Transform; exports.groupD8 = groupD8; },{}],22:[function(require,module,exports){ /*! * @pixi/mesh-extras - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/mesh-extras is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var mesh = require('@pixi/mesh'); var constants = require('@pixi/constants'); var core = require('@pixi/core'); var PlaneGeometry = /*@__PURE__*/(function (MeshGeometry) { function PlaneGeometry(width, height, segWidth, segHeight) { if ( width === void 0 ) width = 100; if ( height === void 0 ) height = 100; if ( segWidth === void 0 ) segWidth = 10; if ( segHeight === void 0 ) segHeight = 10; MeshGeometry.call(this); this.segWidth = segWidth; this.segHeight = segHeight; this.width = width; this.height = height; this.build(); } if ( MeshGeometry ) PlaneGeometry.__proto__ = MeshGeometry; PlaneGeometry.prototype = Object.create( MeshGeometry && MeshGeometry.prototype ); PlaneGeometry.prototype.constructor = PlaneGeometry; /** * Refreshes plane coordinates * @private */ PlaneGeometry.prototype.build = function build () { var total = this.segWidth * this.segHeight; var verts = []; var uvs = []; var indices = []; var segmentsX = this.segWidth - 1; var segmentsY = this.segHeight - 1; var sizeX = (this.width) / segmentsX; var sizeY = (this.height) / segmentsY; for (var i = 0; i < total; i++) { var x = (i % this.segWidth); var y = ((i / this.segWidth) | 0); verts.push(x * sizeX, y * sizeY); uvs.push(x / segmentsX, y / segmentsY); } var totalSub = segmentsX * segmentsY; for (var i$1 = 0; i$1 < totalSub; i$1++) { var xpos = i$1 % segmentsX; var ypos = (i$1 / segmentsX) | 0; var value = (ypos * this.segWidth) + xpos; var value2 = (ypos * this.segWidth) + xpos + 1; var value3 = ((ypos + 1) * this.segWidth) + xpos; var value4 = ((ypos + 1) * this.segWidth) + xpos + 1; indices.push(value, value2, value3, value2, value4, value3); } this.buffers[0].data = new Float32Array(verts); this.buffers[1].data = new Float32Array(uvs); this.indexBuffer.data = new Uint16Array(indices); // ensure that the changes are uploaded this.buffers[0].update(); this.buffers[1].update(); this.indexBuffer.update(); }; return PlaneGeometry; }(mesh.MeshGeometry)); /** * RopeGeometry allows you to draw a geometry across several points and then manipulate these points. * * ```js * for (let i = 0; i < 20; i++) { * points.push(new PIXI.Point(i * 50, 0)); * }; * const rope = new PIXI.RopeGeometry(100, points); * ``` * * @class * @extends PIXI.MeshGeometry * @memberof PIXI * */ var RopeGeometry = /*@__PURE__*/(function (MeshGeometry) { function RopeGeometry(width, points, textureScale) { if ( width === void 0 ) width = 200; if ( textureScale === void 0 ) textureScale = 0; MeshGeometry.call(this, new Float32Array(points.length * 4), new Float32Array(points.length * 4), new Uint16Array((points.length - 1) * 6)); /** * An array of points that determine the rope * @member {PIXI.Point[]} */ this.points = points; /** * The width (i.e., thickness) of the rope. * @member {number} * @readOnly */ this.width = width; /** * Rope texture scale, if zero then the rope texture is stretched. * @member {number} * @readOnly */ this.textureScale = textureScale; this.build(); } if ( MeshGeometry ) RopeGeometry.__proto__ = MeshGeometry; RopeGeometry.prototype = Object.create( MeshGeometry && MeshGeometry.prototype ); RopeGeometry.prototype.constructor = RopeGeometry; /** * Refreshes Rope indices and uvs * @private */ RopeGeometry.prototype.build = function build () { var points = this.points; if (!points) { return; } var vertexBuffer = this.getBuffer('aVertexPosition'); var uvBuffer = this.getBuffer('aTextureCoord'); var indexBuffer = this.getIndex(); // if too little points, or texture hasn't got UVs set yet just move on. if (points.length < 1) { return; } // if the number of points has changed we will need to recreate the arraybuffers if (vertexBuffer.data.length / 4 !== points.length) { vertexBuffer.data = new Float32Array(points.length * 4); uvBuffer.data = new Float32Array(points.length * 4); indexBuffer.data = new Uint16Array((points.length - 1) * 6); } var uvs = uvBuffer.data; var indices = indexBuffer.data; uvs[0] = 0; uvs[1] = 0; uvs[2] = 0; uvs[3] = 1; var amount = 0; var prev = points[0]; var textureWidth = this.width * this.textureScale; var total = points.length; // - 1; for (var i = 0; i < total; i++) { // time to do some smart drawing! var index = i * 4; if (this.textureScale > 0) { // calculate pixel distance from previous point var dx = prev.x - points[i].x; var dy = prev.y - points[i].y; var distance = Math.sqrt((dx * dx) + (dy * dy)); prev = points[i]; amount += distance / textureWidth; } else { // stretch texture amount = i / (total - 1); } uvs[index] = amount; uvs[index + 1] = 0; uvs[index + 2] = amount; uvs[index + 3] = 1; } var indexCount = 0; for (var i$1 = 0; i$1 < total - 1; i$1++) { var index$1 = i$1 * 2; indices[indexCount++] = index$1; indices[indexCount++] = index$1 + 1; indices[indexCount++] = index$1 + 2; indices[indexCount++] = index$1 + 2; indices[indexCount++] = index$1 + 1; indices[indexCount++] = index$1 + 3; } // ensure that the changes are uploaded uvBuffer.update(); indexBuffer.update(); this.updateVertices(); }; /** * refreshes vertices of Rope mesh */ RopeGeometry.prototype.updateVertices = function updateVertices () { var points = this.points; if (points.length < 1) { return; } var lastPoint = points[0]; var nextPoint; var perpX = 0; var perpY = 0; var vertices = this.buffers[0].data; var total = points.length; for (var i = 0; i < total; i++) { var point = points[i]; var index = i * 4; if (i < points.length - 1) { nextPoint = points[i + 1]; } else { nextPoint = point; } perpY = -(nextPoint.x - lastPoint.x); perpX = nextPoint.y - lastPoint.y; var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY)); var num = this.textureScale > 0 ? this.textureScale * this.width / 2 : this.width / 2; perpX /= perpLength; perpY /= perpLength; perpX *= num; perpY *= num; vertices[index] = point.x + perpX; vertices[index + 1] = point.y + perpY; vertices[index + 2] = point.x - perpX; vertices[index + 3] = point.y - perpY; lastPoint = point; } this.buffers[0].update(); }; RopeGeometry.prototype.update = function update () { if (this.textureScale > 0) { this.build(); // we need to update UVs } else { this.updateVertices(); } }; return RopeGeometry; }(mesh.MeshGeometry)); /** * The rope allows you to draw a texture across several points and then manipulate these points * *```js * for (let i = 0; i < 20; i++) { * points.push(new PIXI.Point(i * 50, 0)); * }; * let rope = new PIXI.SimpleRope(PIXI.Texture.from("snake.png"), points); * ``` * * @class * @extends PIXI.Mesh * @memberof PIXI * */ var SimpleRope = /*@__PURE__*/(function (Mesh) { function SimpleRope(texture, points, textureScale) { if ( textureScale === void 0 ) textureScale = 0; var ropeGeometry = new RopeGeometry(texture.height, points, textureScale); var meshMaterial = new mesh.MeshMaterial(texture); if (textureScale > 0) { // attempt to set UV wrapping, will fail on non-power of two textures texture.baseTexture.wrapMode = constants.WRAP_MODES.REPEAT; } Mesh.call(this, ropeGeometry, meshMaterial); /** * re-calculate vertices by rope points each frame * * @member {boolean} */ this.autoUpdate = true; } if ( Mesh ) SimpleRope.__proto__ = Mesh; SimpleRope.prototype = Object.create( Mesh && Mesh.prototype ); SimpleRope.prototype.constructor = SimpleRope; SimpleRope.prototype._render = function _render (renderer) { if (this.autoUpdate || this.geometry.width !== this.shader.texture.height) { this.geometry.width = this.shader.texture.height; this.geometry.update(); } Mesh.prototype._render.call(this, renderer); }; return SimpleRope; }(mesh.Mesh)); /** * The SimplePlane allows you to draw a texture across several points and then manipulate these points * *```js * for (let i = 0; i < 20; i++) { * points.push(new PIXI.Point(i * 50, 0)); * }; * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points); * ``` * * @class * @extends PIXI.Mesh * @memberof PIXI * */ var SimplePlane = /*@__PURE__*/(function (Mesh) { function SimplePlane(texture, verticesX, verticesY) { var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY); var meshMaterial = new mesh.MeshMaterial(core.Texture.WHITE); Mesh.call(this, planeGeometry, meshMaterial); // lets call the setter to ensure all necessary updates are performed this.texture = texture; } if ( Mesh ) SimplePlane.__proto__ = Mesh; SimplePlane.prototype = Object.create( Mesh && Mesh.prototype ); SimplePlane.prototype.constructor = SimplePlane; var prototypeAccessors = { texture: { configurable: true } }; /** * Method used for overrides, to do something in case texture frame was changed. * Meshes based on plane can override it and change more details based on texture. */ SimplePlane.prototype.textureUpdated = function textureUpdated () { this._textureID = this.shader.texture._updateID; this.geometry.width = this.shader.texture.width; this.geometry.height = this.shader.texture.height; this.geometry.build(); }; prototypeAccessors.texture.set = function (value) { // Track texture same way sprite does. // For generated meshes like NineSlicePlane it can change the geometry. // Unfortunately, this method might not work if you directly change texture in material. if (this.shader.texture === value) { return; } this.shader.texture = value; this._textureID = -1; if (value.baseTexture.valid) { this.textureUpdated(); } else { value.once('update', this.textureUpdated, this); } }; prototypeAccessors.texture.get = function () { return this.shader.texture; }; SimplePlane.prototype._render = function _render (renderer) { if (this._textureID !== this.shader.texture._updateID) { this.textureUpdated(); } Mesh.prototype._render.call(this, renderer); }; Object.defineProperties( SimplePlane.prototype, prototypeAccessors ); return SimplePlane; }(mesh.Mesh)); /** * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments. * For more robust customization, use {@link PIXI.Mesh}. * * @class * @extends PIXI.Mesh * @memberof PIXI */ var SimpleMesh = /*@__PURE__*/(function (Mesh) { function SimpleMesh(texture, vertices, uvs, indices, drawMode) { if ( texture === void 0 ) texture = core.Texture.EMPTY; var geometry = new mesh.MeshGeometry(vertices, uvs, indices); geometry.getBuffer('aVertexPosition').static = false; var meshMaterial = new mesh.MeshMaterial(texture); Mesh.call(this, geometry, meshMaterial, null, drawMode); /** * upload vertices buffer each frame * @member {boolean} */ this.autoUpdate = true; } if ( Mesh ) SimpleMesh.__proto__ = Mesh; SimpleMesh.prototype = Object.create( Mesh && Mesh.prototype ); SimpleMesh.prototype.constructor = SimpleMesh; var prototypeAccessors = { vertices: { configurable: true } }; /** * Collection of vertices data. * @member {Float32Array} */ prototypeAccessors.vertices.get = function () { return this.geometry.getBuffer('aVertexPosition').data; }; prototypeAccessors.vertices.set = function (value) { this.geometry.getBuffer('aVertexPosition').data = value; }; SimpleMesh.prototype._render = function _render (renderer) { if (this.autoUpdate) { this.geometry.getBuffer('aVertexPosition').update(); } Mesh.prototype._render.call(this, renderer); }; Object.defineProperties( SimpleMesh.prototype, prototypeAccessors ); return SimpleMesh; }(mesh.Mesh)); var DEFAULT_BORDER_SIZE = 10; /** * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically * *```js * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15); * ``` *
 *      A                          B
 *    +---+----------------------+---+
 *  C | 1 |          2           | 3 |
 *    +---+----------------------+---+
 *    |   |                      |   |
 *    | 4 |          5           | 6 |
 *    |   |                      |   |
 *    +---+----------------------+---+
 *  D | 7 |          8           | 9 |
 *    +---+----------------------+---+

 *  When changing this objects width and/or height:
 *     areas 1 3 7 and 9 will remain unscaled.
 *     areas 2 and 8 will be stretched horizontally
 *     areas 4 and 6 will be stretched vertically
 *     area 5 will be stretched both horizontally and vertically
 * 
* * @class * @extends PIXI.SimplePlane * @memberof PIXI * */ var NineSlicePlane = /*@__PURE__*/(function (SimplePlane) { function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { SimplePlane.call(this, core.Texture.WHITE, 4, 4); this._origWidth = texture.orig.width; this._origHeight = texture.orig.height; /** * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane * * @member {number} * @override */ this._width = this._origWidth; /** * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane * * @member {number} * @override */ this._height = this._origHeight; /** * The width of the left column (a) * * @member {number} * @private */ this._leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; /** * The width of the right column (b) * * @member {number} * @private */ this._rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; /** * The height of the top row (c) * * @member {number} * @private */ this._topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; /** * The height of the bottom row (d) * * @member {number} * @private */ this._bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; // lets call the setter to ensure all necessary updates are performed this.texture = texture; } if ( SimplePlane ) NineSlicePlane.__proto__ = SimplePlane; NineSlicePlane.prototype = Object.create( SimplePlane && SimplePlane.prototype ); NineSlicePlane.prototype.constructor = NineSlicePlane; var prototypeAccessors = { vertices: { configurable: true },width: { configurable: true },height: { configurable: true },leftWidth: { configurable: true },rightWidth: { configurable: true },topHeight: { configurable: true },bottomHeight: { configurable: true } }; NineSlicePlane.prototype.textureUpdated = function textureUpdated () { this._textureID = this.shader.texture._updateID; this._refresh(); }; prototypeAccessors.vertices.get = function () { return this.geometry.getBuffer('aVertexPosition').data; }; prototypeAccessors.vertices.set = function (value) { this.geometry.getBuffer('aVertexPosition').data = value; }; /** * Updates the horizontal vertices. * */ NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices () { var vertices = this.vertices; var scale = this._getMinScale(); vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale); vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; }; /** * Updates the vertical vertices. * */ NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices () { var vertices = this.vertices; var scale = this._getMinScale(); vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale); vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; }; /** * Returns the smaller of a set of vertical and horizontal scale of nine slice corners. * * @return {number} Smaller number of vertical and horizontal scale. * @private */ NineSlicePlane.prototype._getMinScale = function _getMinScale () { var w = this._leftWidth + this._rightWidth; var scaleW = this._width > w ? 1.0 : this._width / w; var h = this._topHeight + this._bottomHeight; var scaleH = this._height > h ? 1.0 : this._height / h; var scale = Math.min(scaleW, scaleH); return scale; }; /** * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane * * @member {number} */ prototypeAccessors.width.get = function () { return this._width; }; prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc { this._width = value; this._refresh(); }; /** * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane * * @member {number} */ prototypeAccessors.height.get = function () { return this._height; }; prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc { this._height = value; this._refresh(); }; /** * The width of the left column * * @member {number} */ prototypeAccessors.leftWidth.get = function () { return this._leftWidth; }; prototypeAccessors.leftWidth.set = function (value) // eslint-disable-line require-jsdoc { this._leftWidth = value; this._refresh(); }; /** * The width of the right column * * @member {number} */ prototypeAccessors.rightWidth.get = function () { return this._rightWidth; }; prototypeAccessors.rightWidth.set = function (value) // eslint-disable-line require-jsdoc { this._rightWidth = value; this._refresh(); }; /** * The height of the top row * * @member {number} */ prototypeAccessors.topHeight.get = function () { return this._topHeight; }; prototypeAccessors.topHeight.set = function (value) // eslint-disable-line require-jsdoc { this._topHeight = value; this._refresh(); }; /** * The height of the bottom row * * @member {number} */ prototypeAccessors.bottomHeight.get = function () { return this._bottomHeight; }; prototypeAccessors.bottomHeight.set = function (value) // eslint-disable-line require-jsdoc { this._bottomHeight = value; this._refresh(); }; /** * Refreshes NineSlicePlane coords. All of them. */ NineSlicePlane.prototype._refresh = function _refresh () { var texture = this.texture; var uvs = this.geometry.buffers[1].data; this._origWidth = texture.orig.width; this._origHeight = texture.orig.height; var _uvw = 1.0 / this._origWidth; var _uvh = 1.0 / this._origHeight; uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth); uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight); this.updateHorizontalVertices(); this.updateVerticalVertices(); this.geometry.buffers[0].update(); this.geometry.buffers[1].update(); }; Object.defineProperties( NineSlicePlane.prototype, prototypeAccessors ); return NineSlicePlane; }(SimplePlane)); exports.NineSlicePlane = NineSlicePlane; exports.PlaneGeometry = PlaneGeometry; exports.RopeGeometry = RopeGeometry; exports.SimpleMesh = SimpleMesh; exports.SimplePlane = SimplePlane; exports.SimpleRope = SimpleRope; },{"@pixi/constants":6,"@pixi/core":7,"@pixi/mesh":23}],23:[function(require,module,exports){ /*! * @pixi/mesh - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/mesh is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var math = require('@pixi/math'); var constants = require('@pixi/constants'); var display = require('@pixi/display'); var settings = require('@pixi/settings'); var utils = require('@pixi/utils'); /** * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space. * * @class * @memberof PIXI */ var MeshBatchUvs = function MeshBatchUvs(uvBuffer, uvMatrix) { /** * Buffer with normalized UV's * @member {PIXI.Buffer} */ this.uvBuffer = uvBuffer; /** * Material UV matrix * @member {PIXI.TextureMatrix} */ this.uvMatrix = uvMatrix; /** * UV Buffer data * @member {Float32Array} * @readonly */ this.data = null; this._bufferUpdateId = -1; this._textureUpdateId = -1; this._updateID = 0; }; /** * updates * * @param {boolean} forceUpdate - force the update */ MeshBatchUvs.prototype.update = function update (forceUpdate) { if (!forceUpdate && this._bufferUpdateId === this.uvBuffer._updateID && this._textureUpdateId === this.uvMatrix._updateID) { return; } this._bufferUpdateId = this.uvBuffer._updateID; this._textureUpdateId = this.uvMatrix._updateID; var data = this.uvBuffer.data; if (!this.data || this.data.length !== data.length) { this.data = new Float32Array(data.length); } this.uvMatrix.multiplyUvs(data, this.data); this._updateID++; }; var tempPoint = new math.Point(); var tempPolygon = new math.Polygon(); /** * Base mesh class. * * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of. * This class assumes a certain level of WebGL knowledge. * If you know a bit this should abstract enough away to make you life easier! * * Pretty much ALL WebGL can be broken down into the following: * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc.. * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry) * - State - This is the state of WebGL required to render the mesh. * * Through a combination of the above elements you can render anything you want, 2D or 3D! * * @class * @extends PIXI.Container * @memberof PIXI */ var Mesh = /*@__PURE__*/(function (Container) { function Mesh(geometry, shader, state, drawMode)// vertices, uvs, indices, drawMode) { if ( drawMode === void 0 ) drawMode = constants.DRAW_MODES.TRIANGLES; Container.call(this); /** * Includes vertex positions, face indices, normals, colors, UVs, and * custom attributes within buffers, reducing the cost of passing all * this data to the GPU. Can be shared between multiple Mesh objects. * @member {PIXI.Geometry} * @readonly */ this.geometry = geometry; geometry.refCount++; /** * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. * Can be shared between multiple Mesh objects. * @member {PIXI.Shader|PIXI.MeshMaterial} */ this.shader = shader; /** * Represents the WebGL state the Mesh required to render, excludes shader and geometry. E.g., * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. * @member {PIXI.State} */ this.state = state || core.State.for2d(); /** * The way the Mesh should be drawn, can be any of the {@link PIXI.DRAW_MODES} constants. * * @member {number} * @see PIXI.DRAW_MODES */ this.drawMode = drawMode; /** * Typically the index of the IndexBuffer where to start drawing. * @member {number} * @default 0 */ this.start = 0; /** * How much of the geometry to draw, by default `0` renders everything. * @member {number} * @default 0 */ this.size = 0; /** * thease are used as easy access for batching * @member {Float32Array} * @private */ this.uvs = null; /** * thease are used as easy access for batching * @member {Uint16Array} * @private */ this.indices = null; /** * this is the caching layer used by the batcher * @member {Float32Array} * @private */ this.vertexData = new Float32Array(1); /** * If geometry is changed used to decide to re-transform * the vertexData. * @member {number} * @private */ this.vertexDirty = 0; this._transformID = -1; // Inherited from DisplayMode, set defaults this.tint = 0xFFFFFF; this.blendMode = constants.BLEND_MODES.NORMAL; /** * Internal roundPixels field * * @member {boolean} * @private */ this._roundPixels = settings.settings.ROUND_PIXELS; /** * Batched UV's are cached for atlas textures * @member {PIXI.MeshBatchUvs} * @private */ this.batchUvs = null; } if ( Container ) Mesh.__proto__ = Container; Mesh.prototype = Object.create( Container && Container.prototype ); Mesh.prototype.constructor = Mesh; var prototypeAccessors = { uvBuffer: { configurable: true },verticesBuffer: { configurable: true },material: { configurable: true },blendMode: { configurable: true },roundPixels: { configurable: true },tint: { configurable: true },texture: { configurable: true } }; /** * To change mesh uv's, change its uvBuffer data and increment its _updateID. * @member {PIXI.Buffer} * @readonly */ prototypeAccessors.uvBuffer.get = function () { return this.geometry.buffers[1]; }; /** * To change mesh vertices, change its uvBuffer data and increment its _updateID. * Incrementing _updateID is optional because most of Mesh objects do it anyway. * @member {PIXI.Buffer} * @readonly */ prototypeAccessors.verticesBuffer.get = function () { return this.geometry.buffers[0]; }; /** * Alias for {@link PIXI.Mesh#shader}. * @member {PIXI.Shader|PIXI.MeshMaterial} */ prototypeAccessors.material.set = function (value) { this.shader = value; }; prototypeAccessors.material.get = function () { return this.shader; }; /** * The blend mode to be applied to the Mesh. Apply a value of * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. * * @member {number} * @default PIXI.BLEND_MODES.NORMAL; * @see PIXI.BLEND_MODES */ prototypeAccessors.blendMode.set = function (value) { this.state.blendMode = value; }; prototypeAccessors.blendMode.get = function () { return this.state.blendMode; }; /** * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. * Advantages can include sharper image quality (like text) and faster rendering on canvas. * The main disadvantage is movement of objects may appear less smooth. * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} * * @member {boolean} * @default false */ prototypeAccessors.roundPixels.set = function (value) { if (this._roundPixels !== value) { this._transformID = -1; } this._roundPixels = value; }; prototypeAccessors.roundPixels.get = function () { return this._roundPixels; }; /** * The multiply tint applied to the Mesh. This is a hex value. A value of * `0xFFFFFF` will remove any tint effect. * * @member {number} * @default 0xFFFFFF */ prototypeAccessors.tint.get = function () { return this.shader.tint; }; prototypeAccessors.tint.set = function (value) { this.shader.tint = value; }; /** * The texture that the Mesh uses. * * @member {PIXI.Texture} */ prototypeAccessors.texture.get = function () { return this.shader.texture; }; prototypeAccessors.texture.set = function (value) { this.shader.texture = value; }; /** * Standard renderer draw. * @protected * @param {PIXI.Renderer} renderer - Instance to renderer. */ Mesh.prototype._render = function _render (renderer) { // set properties for batching.. // TODO could use a different way to grab verts? var vertices = this.geometry.buffers[0].data; // TODO benchmark check for attribute size.. if (this.shader.batchable && this.drawMode === constants.DRAW_MODES.TRIANGLES && vertices.length < Mesh.BATCHABLE_SIZE * 2) { this._renderToBatch(renderer); } else { this._renderDefault(renderer); } }; /** * Standard non-batching way of rendering. * @protected * @param {PIXI.Renderer} renderer - Instance to renderer. */ Mesh.prototype._renderDefault = function _renderDefault (renderer) { var shader = this.shader; shader.alpha = this.worldAlpha; if (shader.update) { shader.update(); } renderer.batch.flush(); if (shader.program.uniformData.translationMatrix) { shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true); } // bind and sync uniforms.. renderer.shader.bind(shader); // set state.. renderer.state.set(this.state); // bind the geometry... renderer.geometry.bind(this.geometry, shader); // then render it renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount); }; /** * Rendering by using the Batch system. * @protected * @param {PIXI.Renderer} renderer - Instance to renderer. */ Mesh.prototype._renderToBatch = function _renderToBatch (renderer) { var geometry = this.geometry; if (this.shader.uvMatrix) { this.shader.uvMatrix.update(); this.calculateUvs(); } // set properties for batching.. this.calculateVertices(); this.indices = geometry.indexBuffer.data; this._tintRGB = this.shader._tintRGB; this._texture = this.shader.texture; var pluginName = this.material.pluginName; renderer.batch.setObjectRenderer(renderer.plugins[pluginName]); renderer.plugins[pluginName].render(this); }; /** * Updates vertexData field based on transform and vertices */ Mesh.prototype.calculateVertices = function calculateVertices () { var geometry = this.geometry; var vertices = geometry.buffers[0].data; if (geometry.vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) { return; } this._transformID = this.transform._worldID; if (this.vertexData.length !== vertices.length) { this.vertexData = new Float32Array(vertices.length); } var wt = this.transform.worldTransform; var a = wt.a; var b = wt.b; var c = wt.c; var d = wt.d; var tx = wt.tx; var ty = wt.ty; var vertexData = this.vertexData; for (var i = 0; i < vertexData.length / 2; i++) { var x = vertices[(i * 2)]; var y = vertices[(i * 2) + 1]; vertexData[(i * 2)] = (a * x) + (c * y) + tx; vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty; } if (this._roundPixels) { var resolution = settings.settings.RESOLUTION; for (var i$1 = 0; i$1 < vertexData.length; ++i$1) { vertexData[i$1] = Math.round((vertexData[i$1] * resolution | 0) / resolution); } } this.vertexDirty = geometry.vertexDirtyId; }; /** * Updates uv field based on from geometry uv's or batchUvs */ Mesh.prototype.calculateUvs = function calculateUvs () { var geomUvs = this.geometry.buffers[1]; if (!this.shader.uvMatrix.isSimple) { if (!this.batchUvs) { this.batchUvs = new MeshBatchUvs(geomUvs, this.shader.uvMatrix); } this.batchUvs.update(); this.uvs = this.batchUvs.data; } else { this.uvs = geomUvs.data; } }; /** * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly. * * @protected */ Mesh.prototype._calculateBounds = function _calculateBounds () { this.calculateVertices(); this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length); }; /** * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES. * * @param {PIXI.Point} point the point to test * @return {boolean} the result of the test */ Mesh.prototype.containsPoint = function containsPoint (point) { if (!this.getBounds().contains(point.x, point.y)) { return false; } this.worldTransform.applyInverse(point, tempPoint); var vertices = this.geometry.getBuffer('aVertexPosition').data; var points = tempPolygon.points; var indices = this.geometry.getIndex().data; var len = indices.length; var step = this.drawMode === 4 ? 3 : 1; for (var i = 0; i + 2 < len; i += step) { var ind0 = indices[i] * 2; var ind1 = indices[i + 1] * 2; var ind2 = indices[i + 2] * 2; points[0] = vertices[ind0]; points[1] = vertices[ind0 + 1]; points[2] = vertices[ind1]; points[3] = vertices[ind1 + 1]; points[4] = vertices[ind2]; points[5] = vertices[ind2 + 1]; if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { return true; } } return false; }; /** * Destroys the Mesh object. * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all * options have been set to that value * @param {boolean} [options.children=false] - if set to true, all the children will have * their destroy method called as well. 'options' will be passed on to those calls. */ Mesh.prototype.destroy = function destroy (options) { Container.prototype.destroy.call(this, options); this.geometry.refCount--; if (this.geometry.refCount === 0) { this.geometry.dispose(); } this.geometry = null; this.shader = null; this.state = null; this.uvs = null; this.indices = null; this.vertexData = null; }; Object.defineProperties( Mesh.prototype, prototypeAccessors ); return Mesh; }(display.Container)); /** * The maximum number of vertices to consider batchable. Generally, the complexity * of the geometry. * @memberof PIXI.Mesh * @static * @member {number} BATCHABLE_SIZE */ Mesh.BATCHABLE_SIZE = 100; var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n"; var fragment = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n"; /** * Slightly opinionated default shader for PixiJS 2D objects. * @class * @memberof PIXI * @extends PIXI.Shader */ var MeshMaterial = /*@__PURE__*/(function (Shader) { function MeshMaterial(uSampler, options) { var uniforms = { uSampler: uSampler, alpha: 1, uTextureMatrix: math.Matrix.IDENTITY, uColor: new Float32Array([1, 1, 1, 1]), }; // Set defaults options = Object.assign({ tint: 0xFFFFFF, alpha: 1, pluginName: 'batch', }, options); if (options.uniforms) { Object.assign(uniforms, options.uniforms); } Shader.call(this, options.program || core.Program.from(vertex, fragment), uniforms); /** * Only do update if tint or alpha changes. * @member {boolean} * @private * @default false */ this._colorDirty = false; /** * TextureMatrix instance for this Mesh, used to track Texture changes * * @member {PIXI.TextureMatrix} * @readonly */ this.uvMatrix = new core.TextureMatrix(uSampler); /** * `true` if shader can be batch with the renderer's batch system. * @member {boolean} * @default true */ this.batchable = options.program === undefined; /** * Renderer plugin for batching * * @member {string} * @default 'batch' */ this.pluginName = options.pluginName; this.tint = options.tint; this.alpha = options.alpha; } if ( Shader ) MeshMaterial.__proto__ = Shader; MeshMaterial.prototype = Object.create( Shader && Shader.prototype ); MeshMaterial.prototype.constructor = MeshMaterial; var prototypeAccessors = { texture: { configurable: true },alpha: { configurable: true },tint: { configurable: true } }; /** * Reference to the texture being rendered. * @member {PIXI.Texture} */ prototypeAccessors.texture.get = function () { return this.uniforms.uSampler; }; prototypeAccessors.texture.set = function (value) { if (this.uniforms.uSampler !== value) { this.uniforms.uSampler = value; this.uvMatrix.texture = value; } }; /** * This gets automatically set by the object using this. * * @default 1 * @member {number} */ prototypeAccessors.alpha.set = function (value) { if (value === this._alpha) { return; } this._alpha = value; this._colorDirty = true; }; prototypeAccessors.alpha.get = function () { return this._alpha; }; /** * Multiply tint for the material. * @member {number} * @default 0xFFFFFF */ prototypeAccessors.tint.set = function (value) { if (value === this._tint) { return; } this._tint = value; this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); this._colorDirty = true; }; prototypeAccessors.tint.get = function () { return this._tint; }; /** * Gets called automatically by the Mesh. Intended to be overridden for custom * MeshMaterial objects. */ MeshMaterial.prototype.update = function update () { if (this._colorDirty) { this._colorDirty = false; var baseTexture = this.texture.baseTexture; utils.premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode); } if (this.uvMatrix.update()) { this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord; } }; Object.defineProperties( MeshMaterial.prototype, prototypeAccessors ); return MeshMaterial; }(core.Shader)); /** * Standard 2D geometry used in PixiJS. * * Geometry can be defined without passing in a style or data if required. * * ```js * const geometry = new PIXI.Geometry(); * * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2); * geometry.addIndex([0,1,2,1,3,2]); * * ``` * @class * @memberof PIXI * @extends PIXI.Geometry */ var MeshGeometry = /*@__PURE__*/(function (Geometry) { function MeshGeometry(vertices, uvs, index) { Geometry.call(this); var verticesBuffer = new core.Buffer(vertices); var uvsBuffer = new core.Buffer(uvs, true); var indexBuffer = new core.Buffer(index, true, true); this.addAttribute('aVertexPosition', verticesBuffer, 2, false, constants.TYPES.FLOAT) .addAttribute('aTextureCoord', uvsBuffer, 2, false, constants.TYPES.FLOAT) .addIndex(indexBuffer); /** * Dirty flag to limit update calls on Mesh. For example, * limiting updates on a single Mesh instance with a shared Geometry * within the render loop. * @private * @member {number} * @default -1 */ this._updateId = -1; } if ( Geometry ) MeshGeometry.__proto__ = Geometry; MeshGeometry.prototype = Object.create( Geometry && Geometry.prototype ); MeshGeometry.prototype.constructor = MeshGeometry; var prototypeAccessors = { vertexDirtyId: { configurable: true } }; /** * If the vertex position is updated. * @member {number} * @readonly * @private */ prototypeAccessors.vertexDirtyId.get = function () { return this.buffers[0]._updateID; }; Object.defineProperties( MeshGeometry.prototype, prototypeAccessors ); return MeshGeometry; }(core.Geometry)); exports.Mesh = Mesh; exports.MeshBatchUvs = MeshBatchUvs; exports.MeshGeometry = MeshGeometry; exports.MeshMaterial = MeshMaterial; },{"@pixi/constants":6,"@pixi/core":7,"@pixi/display":8,"@pixi/math":21,"@pixi/settings":31,"@pixi/utils":39}],24:[function(require,module,exports){ /*! * @pixi/mixin-cache-as-bitmap - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/mixin-cache-as-bitmap is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; var core = require('@pixi/core'); var sprite = require('@pixi/sprite'); var display = require('@pixi/display'); var math = require('@pixi/math'); var utils = require('@pixi/utils'); var settings = require('@pixi/settings'); var _tempMatrix = new math.Matrix(); display.DisplayObject.prototype._cacheAsBitmap = false; display.DisplayObject.prototype._cacheData = false; // figured theres no point adding ALL the extra variables to prototype. // this model can hold the information needed. This can also be generated on demand as // most objects are not cached as bitmaps. /** * @class * @ignore */ var CacheData = function CacheData() { this.textureCacheId = null; this.originalRender = null; this.originalRenderCanvas = null; this.originalCalculateBounds = null; this.originalGetLocalBounds = null; this.originalUpdateTransform = null; this.originalHitTest = null; this.originalDestroy = null; this.originalMask = null; this.originalFilterArea = null; this.sprite = null; }; Object.defineProperties(display.DisplayObject.prototype, { /** * Set this to true if you want this display object to be cached as a bitmap. * This basically takes a snap shot of the display object as it is at that moment. It can * provide a performance benefit for complex static displayObjects. * To remove simply set this property to `false` * * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. * * @member {boolean} * @memberof PIXI.DisplayObject# */ cacheAsBitmap: { get: function get() { return this._cacheAsBitmap; }, set: function set(value) { if (this._cacheAsBitmap === value) { return; } this._cacheAsBitmap = value; var data; if (value) { if (!this._cacheData) { this._cacheData = new CacheData(); } data = this._cacheData; data.originalRender = this.render; data.originalRenderCanvas = this.renderCanvas; data.originalUpdateTransform = this.updateTransform; data.originalCalculateBounds = this.calculateBounds; data.originalGetLocalBounds = this.getLocalBounds; data.originalDestroy = this.destroy; data.originalContainsPoint = this.containsPoint; data.originalMask = this._mask; data.originalFilterArea = this.filterArea; this.render = this._renderCached; this.renderCanvas = this._renderCachedCanvas; this.destroy = this._cacheAsBitmapDestroy; } else { data = this._cacheData; if (data.sprite) { this._destroyCachedDisplayObject(); } this.render = data.originalRender; this.renderCanvas = data.originalRenderCanvas; this.calculateBounds = data.originalCalculateBounds; this.getLocalBounds = data.originalGetLocalBounds; this.destroy = data.originalDestroy; this.updateTransform = data.originalUpdateTransform; this.containsPoint = data.originalContainsPoint; this._mask = data.originalMask; this.filterArea = data.originalFilterArea; } }, }, }); /** * Renders a cached version of the sprite with WebGL * * @private * @function _renderCached * @memberof PIXI.DisplayObject# * @param {PIXI.Renderer} renderer - the WebGL renderer */ display.DisplayObject.prototype._renderCached = function _renderCached(renderer) { if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { return; } this._initCachedDisplayObject(renderer); this._cacheData.sprite.transform._worldID = this.transform._worldID; this._cacheData.sprite.worldAlpha = this.worldAlpha; this._cacheData.sprite._render(renderer); }; /** * Prepares the WebGL renderer to cache the sprite * * @private * @function _initCachedDisplayObject * @memberof PIXI.DisplayObject# * @param {PIXI.Renderer} renderer - the WebGL renderer */ display.DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { if (this._cacheData && this._cacheData.sprite) { return; } // make sure alpha is set to 1 otherwise it will get rendered as invisible! var cacheAlpha = this.alpha; this.alpha = 1; // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) renderer.batch.flush(); // this.filters= []; // next we find the dimensions of the untransformed object // this function also calls updatetransform on all its children as part of the measuring. // This means we don't need to update the transform again in this function // TODO pass an object to clone too? saves having to create a new one each time! var bounds = this.getLocalBounds().clone(); // add some padding! if (this.filters) { var padding = this.filters[0].padding; bounds.pad(padding); } bounds.ceil(settings.settings.RESOLUTION); // for now we cache the current renderTarget that the WebGL renderer is currently using. // this could be more elegant.. var cachedRenderTexture = renderer.renderTexture.current; var cachedSourceFrame = renderer.renderTexture.sourceFrame; var cachedProjectionTransform = renderer.projection.transform; // We also store the filter stack - I will definitely look to change how this works a little later down the line. // const stack = renderer.filterManager.filterStack; // this renderTexture will be used to store the cached DisplayObject var renderTexture = core.RenderTexture.create(bounds.width, bounds.height); var textureCacheId = "cacheAsBitmap_" + (utils.uid()); this._cacheData.textureCacheId = textureCacheId; core.BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); core.Texture.addToCache(renderTexture, textureCacheId); // need to set // var m = _tempMatrix; m.tx = -bounds.x; m.ty = -bounds.y; // reset this.transform.worldTransform.identity(); // set all properties to there original so we can render to a texture this.render = this._cacheData.originalRender; renderer.render(this, renderTexture, true, m, true); // now restore the state be setting the new properties renderer.projection.transform = cachedProjectionTransform; renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame); // renderer.filterManager.filterStack = stack; this.render = this._renderCached; // the rest is the same as for Canvas this.updateTransform = this.displayObjectUpdateTransform; this.calculateBounds = this._calculateCachedBounds; this.getLocalBounds = this._getCachedLocalBounds; this._mask = null; this.filterArea = null; // create our cached sprite var cachedSprite = new sprite.Sprite(renderTexture); cachedSprite.transform.worldTransform = this.transform.worldTransform; cachedSprite.anchor.x = -(bounds.x / bounds.width); cachedSprite.anchor.y = -(bounds.y / bounds.height); cachedSprite.alpha = cacheAlpha; cachedSprite._bounds = this._bounds; this._cacheData.sprite = cachedSprite; this.transform._parentID = -1; // restore the transform of the cached sprite to avoid the nasty flicker.. if (!this.parent) { this.parent = renderer._tempDisplayObjectParent; this.updateTransform(); this.parent = null; } else { this.updateTransform(); } // map the hit test.. this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); }; /** * Renders a cached version of the sprite with canvas * * @private * @function _renderCachedCanvas * @memberof PIXI.DisplayObject# * @param {PIXI.Renderer} renderer - the WebGL renderer */ display.DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { return; } this._initCachedDisplayObjectCanvas(renderer); this._cacheData.sprite.worldAlpha = this.worldAlpha; this._cacheData.sprite._renderCanvas(renderer); }; // TODO this can be the same as the WebGL version.. will need to do a little tweaking first though.. /** * Prepares the Canvas renderer to cache the sprite * * @private * @function _initCachedDisplayObjectCanvas * @memberof PIXI.DisplayObject# * @param {PIXI.Renderer} renderer - the WebGL renderer */ display.DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { if (this._cacheData && this._cacheData.sprite) { return; } // get bounds actually transforms the object for us already! var bounds = this.getLocalBounds(); var cacheAlpha = this.alpha; this.alpha = 1; var cachedRenderTarget = renderer.context; bounds.ceil(settings.settings.RESOLUTION); var renderTexture = core.RenderTexture.create(bounds.width, bounds.height); var textureCacheId = "cacheAsBitmap_" + (utils.uid()); this._cacheData.textureCacheId = textureCacheId; core.BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); core.Texture.addToCache(renderTexture, textureCacheId); // need to set // var m = _tempMatrix; this.transform.localTransform.copyTo(m); m.invert(); m.tx -= bounds.x; m.ty -= bounds.y; // m.append(this.transform.worldTransform.) // set all properties to there original so we can render to a texture this.renderCanvas = this._cacheData.originalRenderCanvas; // renderTexture.render(this, m, true); renderer.render(this, renderTexture, true, m, false); // now restore the state be setting the new properties renderer.context = cachedRenderTarget; this.renderCanvas = this._renderCachedCanvas; // the rest is the same as for WebGL this.updateTransform = this.displayObjectUpdateTransform; this.calculateBounds = this._calculateCachedBounds; this.getLocalBounds = this._getCachedLocalBounds; this._mask = null; this.filterArea = null; // create our cached sprite var cachedSprite = new sprite.Sprite(renderTexture); cachedSprite.transform.worldTransform = this.transform.worldTransform; cachedSprite.anchor.x = -(bounds.x / bounds.width); cachedSprite.anchor.y = -(bounds.y / bounds.height); cachedSprite.alpha = cacheAlpha; cachedSprite._bounds = this._bounds; this._cacheData.sprite = cachedSprite; this.transform._parentID = -1; // restore the transform of the cached sprite to avoid the nasty flicker.. if (!this.parent) { this.parent = renderer._tempDisplayObjectParent; this.updateTransform(); this.parent = null; } else { this.updateTransform(); } // map the hit test.. this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); }; /** * Calculates the bounds of the cached sprite * * @private */ display.DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { this._bounds.clear(); this._cacheData.sprite.transform._worldID = this.transform._worldID; this._cacheData.sprite._calculateBounds(); this._lastBoundsID = this._boundsID; }; /** * Gets the bounds of the cached sprite. * * @private * @return {Rectangle} The local bounds. */ display.DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { return this._cacheData.sprite.getLocalBounds(); }; /** * Destroys the cached sprite. * * @private */ display.DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { this._cacheData.sprite._texture.destroy(true); this._cacheData.sprite = null; core.BaseTexture.removeFromCache(this._cacheData.textureCacheId); core.Texture.removeFromCache(this._cacheData.textureCacheId); this._cacheData.textureCacheId = null; }; /** * Destroys the cached object. * * @private * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options * have been set to that value. * Used when destroying containers, see the Container.destroy method. */ display.DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { this.cacheAsBitmap = false; this.destroy(options); }; },{"@pixi/core":7,"@pixi/display":8,"@pixi/math":21,"@pixi/settings":31,"@pixi/sprite":34,"@pixi/utils":39}],25:[function(require,module,exports){ /*! * @pixi/mixin-get-child-by-name - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/mixin-get-child-by-name is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; var display = require('@pixi/display'); /** * The instance name of the object. * * @memberof PIXI.DisplayObject# * @member {string} name */ display.DisplayObject.prototype.name = null; /** * Returns the display object in the container. * * @method getChildByName * @memberof PIXI.Container# * @param {string} name - Instance name. * @return {PIXI.DisplayObject} The child with the specified name. */ display.Container.prototype.getChildByName = function getChildByName(name) { for (var i = 0; i < this.children.length; i++) { if (this.children[i].name === name) { return this.children[i]; } } return null; }; },{"@pixi/display":8}],26:[function(require,module,exports){ /*! * @pixi/mixin-get-global-position - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/mixin-get-global-position is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; var display = require('@pixi/display'); var math = require('@pixi/math'); /** * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. * * @method getGlobalPosition * @memberof PIXI.DisplayObject# * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to. * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from * being updated. This means the calculation returned MAY be out of date BUT will give you a * nice performance boost. * @return {PIXI.Point} The updated point. */ display.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) { if ( point === void 0 ) point = new math.Point(); if ( skipUpdate === void 0 ) skipUpdate = false; if (this.parent) { this.parent.toGlobal(this.position, point, skipUpdate); } else { point.x = this.position.x; point.y = this.position.y; } return point; }; },{"@pixi/display":8,"@pixi/math":21}],27:[function(require,module,exports){ /*! * @pixi/particles - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/particles is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var constants = require('@pixi/constants'); var utils = require('@pixi/utils'); var display = require('@pixi/display'); var core = require('@pixi/core'); var math = require('@pixi/math'); /** * The ParticleContainer class is a really fast version of the Container built solely for speed, * so use when you need a lot of sprites or particles. * * The tradeoff of the ParticleContainer is that most advanced functionality will not work. * ParticleContainer implements the basic object transform (position, scale, rotation) * and some advanced functionality like tint (as of v4.5.6). * * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. * * It's extremely easy to use: * ```js * let container = new ParticleContainer(); * * for (let i = 0; i < 100; ++i) * { * let sprite = PIXI.Sprite.from("myImage.png"); * container.addChild(sprite); * } * ``` * * And here you have a hundred sprites that will be rendered at the speed of light. * * @class * @extends PIXI.Container * @memberof PIXI */ var ParticleContainer = /*@__PURE__*/(function (Container) { function ParticleContainer(maxSize, properties, batchSize, autoResize) { if ( maxSize === void 0 ) maxSize = 1500; if ( batchSize === void 0 ) batchSize = 16384; if ( autoResize === void 0 ) autoResize = false; Container.call(this); // Making sure the batch size is valid // 65535 is max vertex index in the index buffer (see ParticleRenderer) // so max number of particles is 65536 / 4 = 16384 var maxBatchSize = 16384; if (batchSize > maxBatchSize) { batchSize = maxBatchSize; } /** * Set properties to be dynamic (true) / static (false) * * @member {boolean[]} * @private */ this._properties = [false, true, false, false, false]; /** * @member {number} * @private */ this._maxSize = maxSize; /** * @member {number} * @private */ this._batchSize = batchSize; /** * @member {Array} * @private */ this._buffers = null; /** * for every batch stores _updateID corresponding to the last change in that batch * @member {number[]} * @private */ this._bufferUpdateIDs = []; /** * when child inserted, removed or changes position this number goes up * @member {number[]} * @private */ this._updateID = 0; /** * @member {boolean} * */ this.interactiveChildren = false; /** * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` * to reset the blend mode. * * @member {number} * @default PIXI.BLEND_MODES.NORMAL * @see PIXI.BLEND_MODES */ this.blendMode = constants.BLEND_MODES.NORMAL; /** * If true, container allocates more batches in case there are more than `maxSize` particles. * @member {boolean} * @default false */ this.autoResize = autoResize; /** * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. * Advantages can include sharper image quality (like text) and faster rendering on canvas. * The main disadvantage is movement of objects may appear less smooth. * Default to true here as performance is usually the priority for particles. * * @member {boolean} * @default true */ this.roundPixels = true; /** * The texture used to render the children. * * @readonly * @member {PIXI.BaseTexture} */ this.baseTexture = null; this.setProperties(properties); /** * The tint applied to the container. * This is a hex value. A value of 0xFFFFFF will remove any tint effect. * * @private * @member {number} * @default 0xFFFFFF */ this._tint = 0; this.tintRgb = new Float32Array(4); this.tint = 0xFFFFFF; } if ( Container ) ParticleContainer.__proto__ = Container; ParticleContainer.prototype = Object.create( Container && Container.prototype ); ParticleContainer.prototype.constructor = ParticleContainer; var prototypeAccessors = { tint: { configurable: true } }; /** * Sets the private properties array to dynamic / static based on the passed properties object * * @param {object} properties - The properties to be uploaded */ ParticleContainer.prototype.setProperties = function setProperties (properties) { if (properties) { this._properties[0] = 'vertices' in properties || 'scale' in properties ? !!properties.vertices || !!properties.scale : this._properties[0]; this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; this._properties[4] = 'tint' in properties || 'alpha' in properties ? !!properties.tint || !!properties.alpha : this._properties[4]; } }; /** * Updates the object transform for rendering * * @private */ ParticleContainer.prototype.updateTransform = function updateTransform () { // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.Container.prototype.updateTransform.call( this ); }; /** * The tint applied to the container. This is a hex value. * A value of 0xFFFFFF will remove any tint effect. ** IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. * @member {number} * @default 0xFFFFFF */ prototypeAccessors.tint.get = function () { return this._tint; }; prototypeAccessors.tint.set = function (value) // eslint-disable-line require-jsdoc { this._tint = value; utils.hex2rgb(value, this.tintRgb); }; /** * Renders the container using the WebGL renderer * * @private * @param {PIXI.Renderer} renderer - The webgl renderer */ ParticleContainer.prototype.render = function render (renderer) { var this$1 = this; if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { return; } if (!this.baseTexture) { this.baseTexture = this.children[0]._texture.baseTexture; if (!this.baseTexture.valid) { this.baseTexture.once('update', function () { return this$1.onChildrenChange(0); }); } } renderer.batch.setObjectRenderer(renderer.plugins.particle); renderer.plugins.particle.render(this); }; /** * Set the flag that static data should be updated to true * * @private * @param {number} smallestChildIndex - The smallest child index */ ParticleContainer.prototype.onChildrenChange = function onChildrenChange (smallestChildIndex) { var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); while (this._bufferUpdateIDs.length < bufferIndex) { this._bufferUpdateIDs.push(0); } this._bufferUpdateIDs[bufferIndex] = ++this._updateID; }; ParticleContainer.prototype.dispose = function dispose () { if (this._buffers) { for (var i = 0; i < this._buffers.length; ++i) { this._buffers[i].destroy(); } this._buffers = null; } }; /** * Destroys the container * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options * have been set to that value * @param {boolean} [options.children=false] - if set to true, all the children will have their * destroy method called as well. 'options' will be passed on to those calls. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true * Should it destroy the texture of the child sprite * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true * Should it destroy the base texture of the child sprite */ ParticleContainer.prototype.destroy = function destroy (options) { Container.prototype.destroy.call(this, options); this.dispose(); this._properties = null; this._buffers = null; this._bufferUpdateIDs = null; }; Object.defineProperties( ParticleContainer.prototype, prototypeAccessors ); return ParticleContainer; }(display.Container)); /** * @author Mat Groves * * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ * for creating the original PixiJS version! * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that * they now share 4 bytes on the vertex buffer * * Heavily inspired by LibGDX's ParticleBuffer: * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java */ /** * The particle buffer manages the static and dynamic buffers for a particle container. * * @class * @private * @memberof PIXI */ var ParticleBuffer = function ParticleBuffer(properties, dynamicPropertyFlags, size) { this.geometry = new core.Geometry(); this.indexBuffer = null; /** * The number of particles the buffer can hold * * @private * @member {number} */ this.size = size; /** * A list of the properties that are dynamic. * * @private * @member {object[]} */ this.dynamicProperties = []; /** * A list of the properties that are static. * * @private * @member {object[]} */ this.staticProperties = []; for (var i = 0; i < properties.length; ++i) { var property = properties[i]; // Make copy of properties object so that when we edit the offset it doesn't // change all other instances of the object literal property = { attributeName: property.attributeName, size: property.size, uploadFunction: property.uploadFunction, type: property.type || constants.TYPES.FLOAT, offset: property.offset, }; if (dynamicPropertyFlags[i]) { this.dynamicProperties.push(property); } else { this.staticProperties.push(property); } } this.staticStride = 0; this.staticBuffer = null; this.staticData = null; this.staticDataUint32 = null; this.dynamicStride = 0; this.dynamicBuffer = null; this.dynamicData = null; this.dynamicDataUint32 = null; this._updateID = 0; this.initBuffers(); }; /** * Sets up the renderer context and necessary buffers. * * @private */ ParticleBuffer.prototype.initBuffers = function initBuffers () { var geometry = this.geometry; var dynamicOffset = 0; /** * Holds the indices of the geometry (quads) to draw * * @member {Uint16Array} * @private */ this.indexBuffer = new core.Buffer(utils.createIndicesForQuads(this.size), true, true); geometry.addIndex(this.indexBuffer); this.dynamicStride = 0; for (var i = 0; i < this.dynamicProperties.length; ++i) { var property = this.dynamicProperties[i]; property.offset = dynamicOffset; dynamicOffset += property.size; this.dynamicStride += property.size; } var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); this.dynamicData = new Float32Array(dynBuffer); this.dynamicDataUint32 = new Uint32Array(dynBuffer); this.dynamicBuffer = new core.Buffer(this.dynamicData, false, false); // static // var staticOffset = 0; this.staticStride = 0; for (var i$1 = 0; i$1 < this.staticProperties.length; ++i$1) { var property$1 = this.staticProperties[i$1]; property$1.offset = staticOffset; staticOffset += property$1.size; this.staticStride += property$1.size; } var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); this.staticData = new Float32Array(statBuffer); this.staticDataUint32 = new Uint32Array(statBuffer); this.staticBuffer = new core.Buffer(this.staticData, true, false); for (var i$2 = 0; i$2 < this.dynamicProperties.length; ++i$2) { var property$2 = this.dynamicProperties[i$2]; geometry.addAttribute( property$2.attributeName, this.dynamicBuffer, 0, property$2.type === constants.TYPES.UNSIGNED_BYTE, property$2.type, this.dynamicStride * 4, property$2.offset * 4 ); } for (var i$3 = 0; i$3 < this.staticProperties.length; ++i$3) { var property$3 = this.staticProperties[i$3]; geometry.addAttribute( property$3.attributeName, this.staticBuffer, 0, property$3.type === constants.TYPES.UNSIGNED_BYTE, property$3.type, this.staticStride * 4, property$3.offset * 4 ); } }; /** * Uploads the dynamic properties. * * @private * @param {PIXI.DisplayObject[]} children - The children to upload. * @param {number} startIndex - The index to start at. * @param {number} amount - The number to upload. */ ParticleBuffer.prototype.uploadDynamic = function uploadDynamic (children, startIndex, amount) { for (var i = 0; i < this.dynamicProperties.length; i++) { var property = this.dynamicProperties[i]; property.uploadFunction(children, startIndex, amount, property.type === constants.TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); } this.dynamicBuffer._updateID++; }; /** * Uploads the static properties. * * @private * @param {PIXI.DisplayObject[]} children - The children to upload. * @param {number} startIndex - The index to start at. * @param {number} amount - The number to upload. */ ParticleBuffer.prototype.uploadStatic = function uploadStatic (children, startIndex, amount) { for (var i = 0; i < this.staticProperties.length; i++) { var property = this.staticProperties[i]; property.uploadFunction(children, startIndex, amount, property.type === constants.TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); } this.staticBuffer._updateID++; }; /** * Destroys the ParticleBuffer. * * @private */ ParticleBuffer.prototype.destroy = function destroy () { this.indexBuffer = null; this.dynamicProperties = null; // this.dynamicBuffer.destroy(); this.dynamicBuffer = null; this.dynamicData = null; this.dynamicDataUint32 = null; this.staticProperties = null; // this.staticBuffer.destroy(); this.staticBuffer = null; this.staticData = null; this.staticDataUint32 = null; // all buffers are destroyed inside geometry this.geometry.destroy(); }; var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n vec2 v = vec2(x, y);\n v = v + aPositionCoord;\n\n gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vColor = aColor * uColor;\n}\n"; var fragment = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n gl_FragColor = color;\n}"; /** * @author Mat Groves * * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ * for creating the original PixiJS version! * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now * share 4 bytes on the vertex buffer * * Heavily inspired by LibGDX's ParticleRenderer: * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java */ /** * Renderer for Particles that is designer for speed over feature set. * * @class * @memberof PIXI */ var ParticleRenderer = /*@__PURE__*/(function (ObjectRenderer) { function ParticleRenderer(renderer) { ObjectRenderer.call(this, renderer); // 65535 is max vertex index in the index buffer (see ParticleRenderer) // so max number of particles is 65536 / 4 = 16384 // and max number of element in the index buffer is 16384 * 6 = 98304 // Creating a full index buffer, overhead is 98304 * 2 = 196Ko // let numIndices = 98304; /** * The default shader that is used if a sprite doesn't have a more specific one. * * @member {PIXI.Shader} */ this.shader = null; this.properties = null; this.tempMatrix = new math.Matrix(); this.properties = [ // verticesData { attributeName: 'aVertexPosition', size: 2, uploadFunction: this.uploadVertices, offset: 0, }, // positionData { attributeName: 'aPositionCoord', size: 2, uploadFunction: this.uploadPosition, offset: 0, }, // rotationData { attributeName: 'aRotation', size: 1, uploadFunction: this.uploadRotation, offset: 0, }, // uvsData { attributeName: 'aTextureCoord', size: 2, uploadFunction: this.uploadUvs, offset: 0, }, // tintData { attributeName: 'aColor', size: 1, type: constants.TYPES.UNSIGNED_BYTE, uploadFunction: this.uploadTint, offset: 0, } ]; this.shader = core.Shader.from(vertex, fragment, {}); /** * The WebGL state in which this renderer will work. * * @member {PIXI.State} * @readonly */ this.state = core.State.for2d(); } if ( ObjectRenderer ) ParticleRenderer.__proto__ = ObjectRenderer; ParticleRenderer.prototype = Object.create( ObjectRenderer && ObjectRenderer.prototype ); ParticleRenderer.prototype.constructor = ParticleRenderer; /** * Renders the particle container object. * * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer */ ParticleRenderer.prototype.render = function render (container) { var children = container.children; var maxSize = container._maxSize; var batchSize = container._batchSize; var renderer = this.renderer; var totalChildren = children.length; if (totalChildren === 0) { return; } else if (totalChildren > maxSize && !container.autoResize) { totalChildren = maxSize; } var buffers = container._buffers; if (!buffers) { buffers = container._buffers = this.generateBuffers(container); } var baseTexture = children[0]._texture.baseTexture; // if the uvs have not updated then no point rendering just yet! this.state.blendMode = utils.correctBlendMode(container.blendMode, baseTexture.alphaMode); renderer.state.set(this.state); var gl = renderer.gl; var m = container.worldTransform.copyTo(this.tempMatrix); m.prepend(renderer.globalUniforms.uniforms.projectionMatrix); this.shader.uniforms.translationMatrix = m.toArray(true); this.shader.uniforms.uColor = utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.alphaMode); this.shader.uniforms.uSampler = baseTexture; this.renderer.shader.bind(this.shader); var updateStatic = false; // now lets upload and render the buffers.. for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { var amount = (totalChildren - i); if (amount > batchSize) { amount = batchSize; } if (j >= buffers.length) { buffers.push(this._generateOneMoreBuffer(container)); } var buffer = buffers[j]; // we always upload the dynamic buffer.uploadDynamic(children, i, amount); var bid = container._bufferUpdateIDs[j] || 0; updateStatic = updateStatic || (buffer._updateID < bid); // we only upload the static content when we have to! if (updateStatic) { buffer._updateID = container._updateID; buffer.uploadStatic(children, i, amount); } // bind the buffer renderer.geometry.bind(buffer.geometry); gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); } }; /** * Creates one particle buffer for each child in the container we want to render and updates internal properties * * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer * @return {PIXI.ParticleBuffer[]} The buffers * @private */ ParticleRenderer.prototype.generateBuffers = function generateBuffers (container) { var buffers = []; var size = container._maxSize; var batchSize = container._batchSize; var dynamicPropertyFlags = container._properties; for (var i = 0; i < size; i += batchSize) { buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize)); } return buffers; }; /** * Creates one more particle buffer, because container has autoResize feature * * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer * @return {PIXI.ParticleBuffer} generated buffer * @private */ ParticleRenderer.prototype._generateOneMoreBuffer = function _generateOneMoreBuffer (container) { var batchSize = container._batchSize; var dynamicPropertyFlags = container._properties; return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize); }; /** * Uploads the vertices. * * @param {PIXI.DisplayObject[]} children - the array of display objects to render * @param {number} startIndex - the index to start from in the children array * @param {number} amount - the amount of children that will have their vertices uploaded * @param {number[]} array - The vertices to upload. * @param {number} stride - Stride to use for iteration. * @param {number} offset - Offset to start at. */ ParticleRenderer.prototype.uploadVertices = function uploadVertices (children, startIndex, amount, array, stride, offset) { var w0 = 0; var w1 = 0; var h0 = 0; var h1 = 0; for (var i = 0; i < amount; ++i) { var sprite = children[startIndex + i]; var texture = sprite._texture; var sx = sprite.scale.x; var sy = sprite.scale.y; var trim = texture.trim; var orig = texture.orig; if (trim) { // if the sprite is trimmed and is not a tilingsprite then we need to add the // extra space before transforming the sprite coords.. w1 = trim.x - (sprite.anchor.x * orig.width); w0 = w1 + trim.width; h1 = trim.y - (sprite.anchor.y * orig.height); h0 = h1 + trim.height; } else { w0 = (orig.width) * (1 - sprite.anchor.x); w1 = (orig.width) * -sprite.anchor.x; h0 = orig.height * (1 - sprite.anchor.y); h1 = orig.height * -sprite.anchor.y; } array[offset] = w1 * sx; array[offset + 1] = h1 * sy; array[offset + stride] = w0 * sx; array[offset + stride + 1] = h1 * sy; array[offset + (stride * 2)] = w0 * sx; array[offset + (stride * 2) + 1] = h0 * sy; array[offset + (stride * 3)] = w1 * sx; array[offset + (stride * 3) + 1] = h0 * sy; offset += stride * 4; } }; /** * Uploads the position. * * @param {PIXI.DisplayObject[]} children - the array of display objects to render * @param {number} startIndex - the index to start from in the children array * @param {number} amount - the amount of children that will have their positions uploaded * @param {number[]} array - The vertices to upload. * @param {number} stride - Stride to use for iteration. * @param {number} offset - Offset to start at. */ ParticleRenderer.prototype.uploadPosition = function uploadPosition (children, startIndex, amount, array, stride, offset) { for (var i = 0; i < amount; i++) { var spritePosition = children[startIndex + i].position; array[offset] = spritePosition.x; array[offset + 1] = spritePosition.y; array[offset + stride] = spritePosition.x; array[offset + stride + 1] = spritePosition.y; array[offset + (stride * 2)] = spritePosition.x; array[offset + (stride * 2) + 1] = spritePosition.y; array[offset + (stride * 3)] = spritePosition.x; array[offset + (stride * 3) + 1] = spritePosition.y; offset += stride * 4; } }; /** * Uploads the rotiation. * * @param {PIXI.DisplayObject[]} children - the array of display objects to render * @param {number} startIndex - the index to start from in the children array * @param {number} amount - the amount of children that will have their rotation uploaded * @param {number[]} array - The vertices to upload. * @param {number} stride - Stride to use for iteration. * @param {number} offset - Offset to start at. */ ParticleRenderer.prototype.uploadRotation = function uploadRotation (children, startIndex, amount, array, stride, offset) { for (var i = 0; i < amount; i++) { var spriteRotation = children[startIndex + i].rotation; array[offset] = spriteRotation; array[offset + stride] = spriteRotation; array[offset + (stride * 2)] = spriteRotation; array[offset + (stride * 3)] = spriteRotation; offset += stride * 4; } }; /** * Uploads the Uvs * * @param {PIXI.DisplayObject[]} children - the array of display objects to render * @param {number} startIndex - the index to start from in the children array * @param {number} amount - the amount of children that will have their rotation uploaded * @param {number[]} array - The vertices to upload. * @param {number} stride - Stride to use for iteration. * @param {number} offset - Offset to start at. */ ParticleRenderer.prototype.uploadUvs = function uploadUvs (children, startIndex, amount, array, stride, offset) { for (var i = 0; i < amount; ++i) { var textureUvs = children[startIndex + i]._texture._uvs; if (textureUvs) { array[offset] = textureUvs.x0; array[offset + 1] = textureUvs.y0; array[offset + stride] = textureUvs.x1; array[offset + stride + 1] = textureUvs.y1; array[offset + (stride * 2)] = textureUvs.x2; array[offset + (stride * 2) + 1] = textureUvs.y2; array[offset + (stride * 3)] = textureUvs.x3; array[offset + (stride * 3) + 1] = textureUvs.y3; offset += stride * 4; } else { // TODO you know this can be easier! array[offset] = 0; array[offset + 1] = 0; array[offset + stride] = 0; array[offset + stride + 1] = 0; array[offset + (stride * 2)] = 0; array[offset + (stride * 2) + 1] = 0; array[offset + (stride * 3)] = 0; array[offset + (stride * 3) + 1] = 0; offset += stride * 4; } } }; /** * Uploads the tint. * * @param {PIXI.DisplayObject[]} children - the array of display objects to render * @param {number} startIndex - the index to start from in the children array * @param {number} amount - the amount of children that will have their rotation uploaded * @param {number[]} array - The vertices to upload. * @param {number} stride - Stride to use for iteration. * @param {number} offset - Offset to start at. */ ParticleRenderer.prototype.uploadTint = function uploadTint (children, startIndex, amount, array, stride, offset) { for (var i = 0; i < amount; ++i) { var sprite = children[startIndex + i]; var premultiplied = sprite._texture.baseTexture.alphaMode > 0; var alpha = sprite.alpha; // we dont call extra function if alpha is 1.0, that's faster var argb = alpha < 1.0 && premultiplied ? utils.premultiplyTint(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); array[offset] = argb; array[offset + stride] = argb; array[offset + (stride * 2)] = argb; array[offset + (stride * 3)] = argb; offset += stride * 4; } }; /** * Destroys the ParticleRenderer. */ ParticleRenderer.prototype.destroy = function destroy () { ObjectRenderer.prototype.destroy.call(this); if (this.shader) { this.shader.destroy(); this.shader = null; } this.tempMatrix = null; }; return ParticleRenderer; }(core.ObjectRenderer)); exports.ParticleContainer = ParticleContainer; exports.ParticleRenderer = ParticleRenderer; },{"@pixi/constants":6,"@pixi/core":7,"@pixi/display":8,"@pixi/math":21,"@pixi/utils":39}],28:[function(require,module,exports){ (function (global){ /*! * @pixi/polyfill - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/polyfill is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var es6PromisePolyfill = require('es6-promise-polyfill'); var objectAssign = _interopDefault(require('object-assign')); // Support for IE 9 - 11 which does not include Promises if (!window.Promise) { window.Promise = es6PromisePolyfill.Polyfill; } // References: if (!Object.assign) { Object.assign = objectAssign; } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; // References: // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // https://gist.github.com/1579671 // http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision // https://gist.github.com/timhall/4078614 // https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame // Expected to be used with Browserfiy // Browserify automatically detects the use of `global` and passes the // correct reference of `global`, `self`, and finally `window` var ONE_FRAME_TIME = 16; // Date.now if (!(Date.now && Date.prototype.getTime)) { Date.now = function now() { return new Date().getTime(); }; } // performance.now if (!(commonjsGlobal.performance && commonjsGlobal.performance.now)) { var startTime = Date.now(); if (!commonjsGlobal.performance) { commonjsGlobal.performance = {}; } commonjsGlobal.performance.now = function () { return Date.now() - startTime; }; } // requestAnimationFrame var lastTime = Date.now(); var vendors = ['ms', 'moz', 'webkit', 'o']; for (var x = 0; x < vendors.length && !commonjsGlobal.requestAnimationFrame; ++x) { var p = vendors[x]; commonjsGlobal.requestAnimationFrame = commonjsGlobal[(p + "RequestAnimationFrame")]; commonjsGlobal.cancelAnimationFrame = commonjsGlobal[(p + "CancelAnimationFrame")] || commonjsGlobal[(p + "CancelRequestAnimationFrame")]; } if (!commonjsGlobal.requestAnimationFrame) { commonjsGlobal.requestAnimationFrame = function (callback) { if (typeof callback !== 'function') { throw new TypeError((callback + "is not a function")); } var currentTime = Date.now(); var delay = ONE_FRAME_TIME + lastTime - currentTime; if (delay < 0) { delay = 0; } lastTime = currentTime; return setTimeout(function () { lastTime = Date.now(); callback(performance.now()); }, delay); }; } if (!commonjsGlobal.cancelAnimationFrame) { commonjsGlobal.cancelAnimationFrame = function (id) { return clearTimeout(id); }; } // References: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign if (!Math.sign) { Math.sign = function mathSign(x) { x = Number(x); if (x === 0 || isNaN(x)) { return x; } return x > 0 ? 1 : -1; }; } // References: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger if (!Number.isInteger) { Number.isInteger = function numberIsInteger(value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; }; } if (!window.ArrayBuffer) { window.ArrayBuffer = Array; } if (!window.Float32Array) { window.Float32Array = Array; } if (!window.Uint32Array) { window.Uint32Array = Array; } if (!window.Uint16Array) { window.Uint16Array = Array; } if (!window.Uint8Array) { window.Uint8Array = Array; } if (!window.Int32Array) { window.Int32Array = Array; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"es6-promise-polyfill":52,"object-assign":372}],29:[function(require,module,exports){ /*! * @pixi/prepare - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/prepare is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var settings = require('@pixi/settings'); var core = require('@pixi/core'); var graphics = require('@pixi/graphics'); var ticker = require('@pixi/ticker'); var display = require('@pixi/display'); var text = require('@pixi/text'); /** * Default number of uploads per frame using prepare plugin. * * @static * @memberof PIXI.settings * @name UPLOADS_PER_FRAME * @type {number} * @default 4 */ settings.settings.UPLOADS_PER_FRAME = 4; /** * CountLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified * number of items per frame. * * @class * @memberof PIXI */ var CountLimiter = function CountLimiter(maxItemsPerFrame) { /** * The maximum number of items that can be prepared each frame. * @type {number} * @private */ this.maxItemsPerFrame = maxItemsPerFrame; /** * The number of items that can be prepared in the current frame. * @type {number} * @private */ this.itemsLeft = 0; }; /** * Resets any counting properties to start fresh on a new frame. */ CountLimiter.prototype.beginFrame = function beginFrame () { this.itemsLeft = this.maxItemsPerFrame; }; /** * Checks to see if another item can be uploaded. This should only be called once per item. * @return {boolean} If the item is allowed to be uploaded. */ CountLimiter.prototype.allowedToUpload = function allowedToUpload () { return this.itemsLeft-- > 0; }; /** * The prepare manager provides functionality to upload content to the GPU. * * BasePrepare handles basic queuing functionality and is extended by * {@link PIXI.Prepare} and {@link PIXI.CanvasPrepare} * to provide preparation capabilities specific to their respective renderers. * * @example * // Create a sprite * const sprite = PIXI.Sprite.from('something.png'); * * // Load object into GPU * app.renderer.plugins.prepare.upload(sprite, () => { * * //Texture(s) has been uploaded to GPU * app.stage.addChild(sprite); * * }) * * @abstract * @class * @memberof PIXI */ var BasePrepare = function BasePrepare(renderer) { var this$1 = this; /** * The limiter to be used to control how quickly items are prepared. * @type {PIXI.CountLimiter|PIXI.TimeLimiter} */ this.limiter = new CountLimiter(settings.settings.UPLOADS_PER_FRAME); /** * Reference to the renderer. * @type {PIXI.AbstractRenderer} * @protected */ this.renderer = renderer; /** * The only real difference between CanvasPrepare and Prepare is what they pass * to upload hooks. That different parameter is stored here. * @type {object} * @protected */ this.uploadHookHelper = null; /** * Collection of items to uploads at once. * @type {Array<*>} * @private */ this.queue = []; /** * Collection of additional hooks for finding assets. * @type {Array} * @private */ this.addHooks = []; /** * Collection of additional hooks for processing assets. * @type {Array} * @private */ this.uploadHooks = []; /** * Callback to call after completed. * @type {Array} * @private */ this.completes = []; /** * If prepare is ticking (running). * @type {boolean} * @private */ this.ticking = false; /** * 'bound' call for prepareItems(). * @type {Function} * @private */ this.delayedTick = function () { // unlikely, but in case we were destroyed between tick() and delayedTick() if (!this$1.queue) { return; } this$1.prepareItems(); }; // hooks to find the correct texture this.registerFindHook(findText); this.registerFindHook(findTextStyle); this.registerFindHook(findMultipleBaseTextures); this.registerFindHook(findBaseTexture); this.registerFindHook(findTexture); // upload hooks this.registerUploadHook(drawText); this.registerUploadHook(calculateTextStyle); }; /** * Upload all the textures and graphics to the GPU. * * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - * Either the container or display object to search for items to upload, the items to upload themselves, * or the callback function, if items have been added using `prepare.add`. * @param {Function} [done] - Optional callback when all queued uploads have completed */ BasePrepare.prototype.upload = function upload (item, done) { if (typeof item === 'function') { done = item; item = null; } // If a display object, search for items // that we could upload if (item) { this.add(item); } // Get the items for upload from the display if (this.queue.length) { if (done) { this.completes.push(done); } if (!this.ticking) { this.ticking = true; ticker.Ticker.system.addOnce(this.tick, this, ticker.UPDATE_PRIORITY.UTILITY); } } else if (done) { done(); } }; /** * Handle tick update * * @private */ BasePrepare.prototype.tick = function tick () { setTimeout(this.delayedTick, 0); }; /** * Actually prepare items. This is handled outside of the tick because it will take a while * and we do NOT want to block the current animation frame from rendering. * * @private */ BasePrepare.prototype.prepareItems = function prepareItems () { this.limiter.beginFrame(); // Upload the graphics while (this.queue.length && this.limiter.allowedToUpload()) { var item = this.queue[0]; var uploaded = false; if (item && !item._destroyed) { for (var i = 0, len = this.uploadHooks.length; i < len; i++) { if (this.uploadHooks[i](this.uploadHookHelper, item)) { this.queue.shift(); uploaded = true; break; } } } if (!uploaded) { this.queue.shift(); } } // We're finished if (!this.queue.length) { this.ticking = false; var completes = this.completes.slice(0); this.completes.length = 0; for (var i$1 = 0, len$1 = completes.length; i$1 < len$1; i$1++) { completes[i$1](); } } else { // if we are not finished, on the next rAF do this again ticker.Ticker.system.addOnce(this.tick, this, ticker.UPDATE_PRIORITY.UTILITY); } }; /** * Adds hooks for finding items. * * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` * function must return `true` if it was able to add item to the queue. * @return {this} Instance of plugin for chaining. */ BasePrepare.prototype.registerFindHook = function registerFindHook (addHook) { if (addHook) { this.addHooks.push(addHook); } return this; }; /** * Adds hooks for uploading items. * * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and * function must return `true` if it was able to handle upload of item. * @return {this} Instance of plugin for chaining. */ BasePrepare.prototype.registerUploadHook = function registerUploadHook (uploadHook) { if (uploadHook) { this.uploadHooks.push(uploadHook); } return this; }; /** * Manually add an item to the uploading queue. * * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to * add to the queue * @return {this} Instance of plugin for chaining. */ BasePrepare.prototype.add = function add (item) { // Add additional hooks for finding elements on special // types of objects that for (var i = 0, len = this.addHooks.length; i < len; i++) { if (this.addHooks[i](item, this.queue)) { break; } } // Get children recursively if (item instanceof display.Container) { for (var i$1 = item.children.length - 1; i$1 >= 0; i$1--) { this.add(item.children[i$1]); } } return this; }; /** * Destroys the plugin, don't use after this. * */ BasePrepare.prototype.destroy = function destroy () { if (this.ticking) { ticker.Ticker.system.remove(this.tick, this); } this.ticking = false; this.addHooks = null; this.uploadHooks = null; this.renderer = null; this.completes = null; this.queue = null; this.limiter = null; this.uploadHookHelper = null; }; /** * Built-in hook to find multiple textures from objects like AnimatedSprites. * * @private * @param {PIXI.DisplayObject} item - Display object to check * @param {Array<*>} queue - Collection of items to upload * @return {boolean} if a PIXI.Texture object was found. */ function findMultipleBaseTextures(item, queue) { var result = false; // Objects with multiple textures if (item && item._textures && item._textures.length) { for (var i = 0; i < item._textures.length; i++) { if (item._textures[i] instanceof core.Texture) { var baseTexture = item._textures[i].baseTexture; if (queue.indexOf(baseTexture) === -1) { queue.push(baseTexture); result = true; } } } } return result; } /** * Built-in hook to find BaseTextures from Texture. * * @private * @param {PIXI.Texture} item - Display object to check * @param {Array<*>} queue - Collection of items to upload * @return {boolean} if a PIXI.Texture object was found. */ function findBaseTexture(item, queue) { if (item.baseTexture instanceof core.BaseTexture) { var texture = item.baseTexture; if (queue.indexOf(texture) === -1) { queue.push(texture); } return true; } return false; } /** * Built-in hook to find textures from objects. * * @private * @param {PIXI.DisplayObject} item - Display object to check * @param {Array<*>} queue - Collection of items to upload * @return {boolean} if a PIXI.Texture object was found. */ function findTexture(item, queue) { if (item._texture && item._texture instanceof core.Texture) { var texture = item._texture.baseTexture; if (queue.indexOf(texture) === -1) { queue.push(texture); } return true; } return false; } /** * Built-in hook to draw PIXI.Text to its texture. * * @private * @param {PIXI.Renderer|PIXI.CanvasPrepare} helper - Not used by this upload handler * @param {PIXI.DisplayObject} item - Item to check * @return {boolean} If item was uploaded. */ function drawText(helper, item) { if (item instanceof text.Text) { // updating text will return early if it is not dirty item.updateText(true); return true; } return false; } /** * Built-in hook to calculate a text style for a PIXI.Text object. * * @private * @param {PIXI.Renderer|PIXI.CanvasPrepare} helper - Not used by this upload handler * @param {PIXI.DisplayObject} item - Item to check * @return {boolean} If item was uploaded. */ function calculateTextStyle(helper, item) { if (item instanceof text.TextStyle) { var font = item.toFontString(); text.TextMetrics.measureFont(font); return true; } return false; } /** * Built-in hook to find Text objects. * * @private * @param {PIXI.DisplayObject} item - Display object to check * @param {Array<*>} queue - Collection of items to upload * @return {boolean} if a PIXI.Text object was found. */ function findText(item, queue) { if (item instanceof text.Text) { // push the text style to prepare it - this can be really expensive if (queue.indexOf(item.style) === -1) { queue.push(item.style); } // also push the text object so that we can render it (to canvas/texture) if needed if (queue.indexOf(item) === -1) { queue.push(item); } // also push the Text's texture for upload to GPU var texture = item._texture.baseTexture; if (queue.indexOf(texture) === -1) { queue.push(texture); } return true; } return false; } /** * Built-in hook to find TextStyle objects. * * @private * @param {PIXI.TextStyle} item - Display object to check * @param {Array<*>} queue - Collection of items to upload * @return {boolean} if a PIXI.TextStyle object was found. */ function findTextStyle(item, queue) { if (item instanceof text.TextStyle) { if (queue.indexOf(item) === -1) { queue.push(item); } return true; } return false; } /** * The prepare plugin provides renderer-specific plugins for pre-rendering DisplayObjects. These plugins are useful for * asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed. * * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. * @example * // Create a new application * const app = new PIXI.Application(); * document.body.appendChild(app.view); * * // Don't start rendering right away * app.stop(); * * // create a display object * const rect = new PIXI.Graphics() * .beginFill(0x00ff00) * .drawRect(40, 40, 200, 200); * * // Add to the stage * app.stage.addChild(rect); * * // Don't start rendering until the graphic is uploaded to the GPU * app.renderer.plugins.prepare.upload(app.stage, () => { * app.start(); * }); * * @class * @extends PIXI.BasePrepare * @memberof PIXI */ var Prepare = /*@__PURE__*/(function (BasePrepare) { function Prepare(renderer) { BasePrepare.call(this, renderer); this.uploadHookHelper = this.renderer; // Add textures and graphics to upload this.registerFindHook(findGraphics); this.registerUploadHook(uploadBaseTextures); this.registerUploadHook(uploadGraphics); } if ( BasePrepare ) Prepare.__proto__ = BasePrepare; Prepare.prototype = Object.create( BasePrepare && BasePrepare.prototype ); Prepare.prototype.constructor = Prepare; return Prepare; }(BasePrepare)); /** * Built-in hook to upload PIXI.Texture objects to the GPU. * * @private * @param {PIXI.Renderer} renderer - instance of the webgl renderer * @param {PIXI.BaseTexture} item - Item to check * @return {boolean} If item was uploaded. */ function uploadBaseTextures(renderer, item) { if (item instanceof core.BaseTexture) { // if the texture already has a GL texture, then the texture has been prepared or rendered // before now. If the texture changed, then the changer should be calling texture.update() which // reuploads the texture without need for preparing it again if (!item._glTextures[renderer.CONTEXT_UID]) { renderer.texture.bind(item); } return true; } return false; } /** * Built-in hook to upload PIXI.Graphics to the GPU. * * @private * @param {PIXI.Renderer} renderer - instance of the webgl renderer * @param {PIXI.DisplayObject} item - Item to check * @return {boolean} If item was uploaded. */ function uploadGraphics(renderer, item) { if (!(item instanceof graphics.Graphics)) { return false; } var geometry = item.geometry; // update dirty graphics to get batches item.finishPoly(); geometry.updateBatches(); var batches = geometry.batches; // upload all textures found in styles for (var i = 0; i < batches.length; i++) { var ref = batches[i].style; var texture = ref.texture; if (texture) { uploadBaseTextures(renderer, texture.baseTexture); } } // if its not batchable - update vao for particular shader if (!geometry.batchable) { renderer.geometry.bind(geometry, item._resolveDirectShader()); } return true; } /** * Built-in hook to find graphics. * * @private * @param {PIXI.DisplayObject} item - Display object to check * @param {Array<*>} queue - Collection of items to upload * @return {boolean} if a PIXI.Graphics object was found. */ function findGraphics(item, queue) { if (item instanceof graphics.Graphics) { queue.push(item); return true; } return false; } /** * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified * number of milliseconds per frame. * * @class * @memberof PIXI */ var TimeLimiter = function TimeLimiter(maxMilliseconds) { /** * The maximum milliseconds that can be spent preparing items each frame. * @type {number} * @private */ this.maxMilliseconds = maxMilliseconds; /** * The start time of the current frame. * @type {number} * @private */ this.frameStart = 0; }; /** * Resets any counting properties to start fresh on a new frame. */ TimeLimiter.prototype.beginFrame = function beginFrame () { this.frameStart = Date.now(); }; /** * Checks to see if another item can be uploaded. This should only be called once per item. * @return {boolean} If the item is allowed to be uploaded. */ TimeLimiter.prototype.allowedToUpload = function allowedToUpload () { return Date.now() - this.frameStart < this.maxMilliseconds; }; exports.BasePrepare = BasePrepare; exports.CountLimiter = CountLimiter; exports.Prepare = Prepare; exports.TimeLimiter = TimeLimiter; },{"@pixi/core":7,"@pixi/display":8,"@pixi/graphics":18,"@pixi/settings":31,"@pixi/text":37,"@pixi/ticker":38}],30:[function(require,module,exports){ /*! * @pixi/runner - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/runner is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * A Runner is a highly performant and simple alternative to signals. Best used in situations * where events are dispatched to many objects at high frequency (say every frame!) * * * like a signal.. * ``` * import { Runner } from '@pixi/runner'; * * const myObject = { * loaded: new Runner('loaded') * } * * const listener = { * loaded: function(){ * // thin * } * } * * myObject.update.add(listener); * * myObject.loaded.emit(); * ``` * * Or for handling calling the same function on many items * ``` * import { Runner } from '@pixi/runner'; * * const myGame = { * update: new Runner('update') * } * * const gameObject = { * update: function(time){ * // update my gamey state * } * } * * myGame.update.add(gameObject1); * * myGame.update.emit(time); * ``` * @class * @memberof PIXI */ var Runner = /** @class */ (function () { /** * @param {string} name the function name that will be executed on the listeners added to this Runner. */ function Runner(name) { this.items = []; this._name = name; this._aliasCount = 0; } /** * Dispatch/Broadcast Runner to all listeners added to the queue. * @param {...any} params - optional parameters to pass to each listener * @return {PIXI.Runner} */ Runner.prototype.emit = function (a0, a1, a2, a3, a4, a5, a6, a7) { if (arguments.length > 8) { throw new Error('max arguments reached'); } var _a = this, name = _a.name, items = _a.items; this._aliasCount++; for (var i = 0, len = items.length; i < len; i++) { items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); } if (items === this.items) { this._aliasCount--; } return this; }; Runner.prototype.ensureNonAliasedItems = function () { if (this._aliasCount > 0 && this.items.length > 1) { this._aliasCount = 0; this.items = this.items.slice(0); } }; /** * Add a listener to the Runner * * Runners do not need to have scope or functions passed to them. * All that is required is to pass the listening object and ensure that it has contains a function that has the same name * as the name provided to the Runner when it was created. * * Eg A listener passed to this Runner will require a 'complete' function. * * ``` * import { Runner } from '@pixi/runner'; * * const complete = new Runner('complete'); * ``` * * The scope used will be the object itself. * * @param {any} item - The object that will be listening. * @return {PIXI.Runner} */ Runner.prototype.add = function (item) { if (item[this._name]) { this.ensureNonAliasedItems(); this.remove(item); this.items.push(item); } return this; }; /** * Remove a single listener from the dispatch queue. * @param {any} item - The listenr that you would like to remove. * @return {PIXI.Runner} */ Runner.prototype.remove = function (item) { var index = this.items.indexOf(item); if (index !== -1) { this.ensureNonAliasedItems(); this.items.splice(index, 1); } return this; }; /** * Check to see if the listener is already in the Runner * @param {any} item - The listener that you would like to check. */ Runner.prototype.contains = function (item) { return this.items.indexOf(item) !== -1; }; /** * Remove all listeners from the Runner * @return {PIXI.Runner} */ Runner.prototype.removeAll = function () { this.ensureNonAliasedItems(); this.items.length = 0; return this; }; /** * Remove all references, don't use after this. */ Runner.prototype.destroy = function () { this.removeAll(); this.items = null; this._name = null; }; Object.defineProperty(Runner.prototype, "empty", { /** * `true` if there are no this Runner contains no listeners * * @member {boolean} * @readonly */ get: function () { return this.items.length === 0; }, enumerable: true, configurable: true }); Object.defineProperty(Runner.prototype, "name", { /** * The name of the runner. * * @member {string} * @readonly */ get: function () { return this._name; }, enumerable: true, configurable: true }); return Runner; }()); Object.defineProperties(Runner.prototype, { /** * Alias for `emit` * @memberof PIXI.Runner# * @method dispatch * @see PIXI.Runner#emit */ dispatch: { value: Runner.prototype.emit }, /** * Alias for `emit` * @memberof PIXI.Runner# * @method run * @see PIXI.Runner#emit */ run: { value: Runner.prototype.emit }, }); exports.Runner = Runner; },{}],31:[function(require,module,exports){ /*! * @pixi/settings - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/settings is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var isMobileCall = _interopDefault(require('ismobilejs')); // The ESM/CJS versions of ismobilejs only var isMobile = isMobileCall(); /** * The maximum recommended texture units to use. * In theory the bigger the better, and for desktop we'll use as many as we can. * But some mobile devices slow down if there is to many branches in the shader. * So in practice there seems to be a sweet spot size that varies depending on the device. * * In v4, all mobile devices were limited to 4 texture units because for this. * In v5, we allow all texture units to be used on modern Apple or Android devices. * * @private * @param {number} max * @returns {number} */ function maxRecommendedTextures(max) { var allowMax = true; if (isMobile.tablet || isMobile.phone) { allowMax = false; if (isMobile.apple.device) { var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/); if (match) { var majorVersion = parseInt(match[1], 10); // All texture units can be used on devices that support ios 11 or above if (majorVersion >= 11) { allowMax = true; } } } if (isMobile.android.device) { var match$1 = (navigator.userAgent).match(/Android\s([0-9.]*)/); if (match$1) { var majorVersion$1 = parseInt(match$1[1], 10); // All texture units can be used on devices that support Android 7 (Nougat) or above if (majorVersion$1 >= 7) { allowMax = true; } } } } return allowMax ? max : 4; } /** * Uploading the same buffer multiple times in a single frame can cause performance issues. * Apparent on iOS so only check for that at the moment * This check may become more complex if this issue pops up elsewhere. * * @private * @returns {boolean} */ function canUploadSameBuffer() { return !isMobile.apple.device; } /** * User's customizable globals for overriding the default PIXI settings, such * as a renderer's default resolution, framerate, float precision, etc. * @example * // Use the native window resolution as the default resolution * // will support high-density displays when rendering * PIXI.settings.RESOLUTION = window.devicePixelRatio; * * // Disable interpolation when scaling, will make texture be pixelated * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; * @namespace PIXI.settings */ var settings = { /** * If set to true WebGL will attempt make textures mimpaped by default. * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. * * @static * @name MIPMAP_TEXTURES * @memberof PIXI.settings * @type {PIXI.MIPMAP_MODES} * @default PIXI.MIPMAP_MODES.POW2 */ MIPMAP_TEXTURES: 1, /** * Default anisotropic filtering level of textures. * Usually from 0 to 16 * * @static * @name ANISOTROPIC_LEVEL * @memberof PIXI.settings * @type {number} * @default 0 */ ANISOTROPIC_LEVEL: 0, /** * Default resolution / device pixel ratio of the renderer. * * @static * @name RESOLUTION * @memberof PIXI.settings * @type {number} * @default 1 */ RESOLUTION: 1, /** * Default filter resolution. * * @static * @name FILTER_RESOLUTION * @memberof PIXI.settings * @type {number} * @default 1 */ FILTER_RESOLUTION: 1, /** * The maximum textures that this device supports. * * @static * @name SPRITE_MAX_TEXTURES * @memberof PIXI.settings * @type {number} * @default 32 */ SPRITE_MAX_TEXTURES: maxRecommendedTextures(32), // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 /** * The default sprite batch size. * * The default aims to balance desktop and mobile devices. * * @static * @name SPRITE_BATCH_SIZE * @memberof PIXI.settings * @type {number} * @default 4096 */ SPRITE_BATCH_SIZE: 4096, /** * The default render options if none are supplied to {@link PIXI.Renderer} * or {@link PIXI.CanvasRenderer}. * * @static * @name RENDER_OPTIONS * @memberof PIXI.settings * @type {object} * @property {HTMLCanvasElement} view=null * @property {number} resolution=1 * @property {boolean} antialias=false * @property {boolean} forceFXAA=false * @property {boolean} autoDensity=false * @property {boolean} transparent=false * @property {number} backgroundColor=0x000000 * @property {boolean} clearBeforeRender=true * @property {boolean} preserveDrawingBuffer=false * @property {number} width=800 * @property {number} height=600 * @property {boolean} legacy=false */ RENDER_OPTIONS: { view: null, antialias: false, forceFXAA: false, autoDensity: false, transparent: false, backgroundColor: 0x000000, clearBeforeRender: true, preserveDrawingBuffer: false, width: 800, height: 600, legacy: false, }, /** * Default Garbage Collection mode. * * @static * @name GC_MODE * @memberof PIXI.settings * @type {PIXI.GC_MODES} * @default PIXI.GC_MODES.AUTO */ GC_MODE: 0, /** * Default Garbage Collection max idle. * * @static * @name GC_MAX_IDLE * @memberof PIXI.settings * @type {number} * @default 3600 */ GC_MAX_IDLE: 60 * 60, /** * Default Garbage Collection maximum check count. * * @static * @name GC_MAX_CHECK_COUNT * @memberof PIXI.settings * @type {number} * @default 600 */ GC_MAX_CHECK_COUNT: 60 * 10, /** * Default wrap modes that are supported by pixi. * * @static * @name WRAP_MODE * @memberof PIXI.settings * @type {PIXI.WRAP_MODES} * @default PIXI.WRAP_MODES.CLAMP */ WRAP_MODE: 33071, /** * Default scale mode for textures. * * @static * @name SCALE_MODE * @memberof PIXI.settings * @type {PIXI.SCALE_MODES} * @default PIXI.SCALE_MODES.LINEAR */ SCALE_MODE: 1, /** * Default specify float precision in vertex shader. * * @static * @name PRECISION_VERTEX * @memberof PIXI.settings * @type {PIXI.PRECISION} * @default PIXI.PRECISION.HIGH */ PRECISION_VERTEX: 'highp', /** * Default specify float precision in fragment shader. * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742 * * @static * @name PRECISION_FRAGMENT * @memberof PIXI.settings * @type {PIXI.PRECISION} * @default PIXI.PRECISION.MEDIUM */ PRECISION_FRAGMENT: isMobile.apple.device ? 'highp' : 'mediump', /** * Can we upload the same buffer in a single frame? * * @static * @name CAN_UPLOAD_SAME_BUFFER * @memberof PIXI.settings * @type {boolean} */ CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(), /** * Enables bitmap creation before image load. This feature is experimental. * * @static * @name CREATE_IMAGE_BITMAP * @memberof PIXI.settings * @type {boolean} * @default false */ CREATE_IMAGE_BITMAP: false, /** * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. * Advantages can include sharper image quality (like text) and faster rendering on canvas. * The main disadvantage is movement of objects may appear less smooth. * * @static * @constant * @memberof PIXI.settings * @type {boolean} * @default false */ ROUND_PIXELS: false, }; exports.isMobile = isMobile; exports.settings = settings; },{"ismobilejs":114}],32:[function(require,module,exports){ /*! * @pixi/sprite-animated - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/sprite-animated is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var sprite = require('@pixi/sprite'); var ticker = require('@pixi/ticker'); /** * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. * * ```js * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; * let textureArray = []; * * for (let i=0; i < 4; i++) * { * let texture = PIXI.Texture.from(alienImages[i]); * textureArray.push(texture); * }; * * let animatedSprite = new PIXI.AnimatedSprite(textureArray); * ``` * * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} * containing the animation definitions: * * ```js * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); * * function setup() { * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; * animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]); * ... * } * ``` * * @class * @extends PIXI.Sprite * @memberof PIXI */ var AnimatedSprite = /*@__PURE__*/(function (Sprite) { function AnimatedSprite(textures, autoUpdate) { Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture); /** * @type {PIXI.Texture[]} * @private */ this._textures = null; /** * @type {number[]} * @private */ this._durations = null; this.textures = textures; /** * `true` uses PIXI.Ticker.shared to auto update animation time. * @type {boolean} * @default true * @private */ this._autoUpdate = autoUpdate !== false; /** * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower. * * @member {number} * @default 1 */ this.animationSpeed = 1; /** * Whether or not the animate sprite repeats after playing. * * @member {boolean} * @default true */ this.loop = true; /** * Update anchor to [Texture's defaultAnchor]{@link PIXI.Texture#defaultAnchor} when frame changes. * * Useful with [sprite sheet animations]{@link PIXI.Spritesheet#animations} created with tools. * Changing anchor for each frame allows to pin sprite origin to certain moving feature * of the frame (e.g. left foot). * * Note: Enabling this will override any previously set `anchor` on each frame change. * * @member {boolean} * @default false */ this.updateAnchor = false; /** * Function to call when an AnimatedSprite finishes playing. * * @member {Function} */ this.onComplete = null; /** * Function to call when an AnimatedSprite changes which texture is being rendered. * * @member {Function} */ this.onFrameChange = null; /** * Function to call when `loop` is true, and an AnimatedSprite is played and loops around to start again. * * @member {Function} */ this.onLoop = null; /** * Elapsed time since animation has been started, used internally to display current texture. * * @member {number} * @private */ this._currentTime = 0; /** * Indicates if the AnimatedSprite is currently playing. * * @member {boolean} * @readonly */ this.playing = false; } if ( Sprite ) AnimatedSprite.__proto__ = Sprite; AnimatedSprite.prototype = Object.create( Sprite && Sprite.prototype ); AnimatedSprite.prototype.constructor = AnimatedSprite; var prototypeAccessors = { totalFrames: { configurable: true },textures: { configurable: true },currentFrame: { configurable: true } }; /** * Stops the AnimatedSprite. * */ AnimatedSprite.prototype.stop = function stop () { if (!this.playing) { return; } this.playing = false; if (this._autoUpdate) { ticker.Ticker.shared.remove(this.update, this); } }; /** * Plays the AnimatedSprite. * */ AnimatedSprite.prototype.play = function play () { if (this.playing) { return; } this.playing = true; if (this._autoUpdate) { ticker.Ticker.shared.add(this.update, this, ticker.UPDATE_PRIORITY.HIGH); } }; /** * Stops the AnimatedSprite and goes to a specific frame. * * @param {number} frameNumber - Frame index to stop at. */ AnimatedSprite.prototype.gotoAndStop = function gotoAndStop (frameNumber) { this.stop(); var previousFrame = this.currentFrame; this._currentTime = frameNumber; if (previousFrame !== this.currentFrame) { this.updateTexture(); } }; /** * Goes to a specific frame and begins playing the AnimatedSprite. * * @param {number} frameNumber - Frame index to start at. */ AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay (frameNumber) { var previousFrame = this.currentFrame; this._currentTime = frameNumber; if (previousFrame !== this.currentFrame) { this.updateTexture(); } this.play(); }; /** * Updates the object transform for rendering. * * @private * @param {number} deltaTime - Time since last tick. */ AnimatedSprite.prototype.update = function update (deltaTime) { var elapsed = this.animationSpeed * deltaTime; var previousFrame = this.currentFrame; if (this._durations !== null) { var lag = this._currentTime % 1 * this._durations[this.currentFrame]; lag += elapsed / 60 * 1000; while (lag < 0) { this._currentTime--; lag += this._durations[this.currentFrame]; } var sign = Math.sign(this.animationSpeed * deltaTime); this._currentTime = Math.floor(this._currentTime); while (lag >= this._durations[this.currentFrame]) { lag -= this._durations[this.currentFrame] * sign; this._currentTime += sign; } this._currentTime += lag / this._durations[this.currentFrame]; } else { this._currentTime += elapsed; } if (this._currentTime < 0 && !this.loop) { this._currentTime = 0; this.stop(); if (this.onComplete) { this.onComplete(); } } else if (this._currentTime >= this._textures.length && !this.loop) { this._currentTime = this._textures.length - 1; this.stop(); if (this.onComplete) { this.onComplete(); } } else if (previousFrame !== this.currentFrame) { if (this.loop && this.onLoop) { if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { this.onLoop(); } else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { this.onLoop(); } } this.updateTexture(); } }; /** * Updates the displayed texture to match the current frame index. * * @private */ AnimatedSprite.prototype.updateTexture = function updateTexture () { this._texture = this._textures[this.currentFrame]; this._textureID = -1; this._textureTrimmedID = -1; this._cachedTint = 0xFFFFFF; this.uvs = this._texture._uvs.uvsFloat32; if (this.updateAnchor) { this._anchor.copyFrom(this._texture.defaultAnchor); } if (this.onFrameChange) { this.onFrameChange(this.currentFrame); } }; /** * Stops the AnimatedSprite and destroys it. * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options * have been set to that value. * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy * method called as well. 'options' will be passed on to those calls. * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well. * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well. */ AnimatedSprite.prototype.destroy = function destroy (options) { this.stop(); Sprite.prototype.destroy.call(this, options); this.onComplete = null; this.onFrameChange = null; this.onLoop = null; }; /** * A short hand way of creating an AnimatedSprite from an array of frame ids. * * @static * @param {string[]} frames - The array of frames ids the AnimatedSprite will use as its texture frames. * @return {AnimatedSprite} The new animated sprite with the specified frames. */ AnimatedSprite.fromFrames = function fromFrames (frames) { var textures = []; for (var i = 0; i < frames.length; ++i) { textures.push(core.Texture.from(frames[i])); } return new AnimatedSprite(textures); }; /** * A short hand way of creating an AnimatedSprite from an array of image ids. * * @static * @param {string[]} images - The array of image urls the AnimatedSprite will use as its texture frames. * @return {AnimatedSprite} The new animate sprite with the specified images as frames. */ AnimatedSprite.fromImages = function fromImages (images) { var textures = []; for (var i = 0; i < images.length; ++i) { textures.push(core.Texture.from(images[i])); } return new AnimatedSprite(textures); }; /** * The total number of frames in the AnimatedSprite. This is the same as number of textures * assigned to the AnimatedSprite. * * @readonly * @member {number} * @default 0 */ prototypeAccessors.totalFrames.get = function () { return this._textures.length; }; /** * The array of textures used for this AnimatedSprite. * * @member {PIXI.Texture[]} */ prototypeAccessors.textures.get = function () { return this._textures; }; prototypeAccessors.textures.set = function (value) // eslint-disable-line require-jsdoc { if (value[0] instanceof core.Texture) { this._textures = value; this._durations = null; } else { this._textures = []; this._durations = []; for (var i = 0; i < value.length; i++) { this._textures.push(value[i].texture); this._durations.push(value[i].time); } } this.gotoAndStop(0); this.updateTexture(); }; /** * The AnimatedSprites current frame index. * * @member {number} * @readonly */ prototypeAccessors.currentFrame.get = function () { var currentFrame = Math.floor(this._currentTime) % this._textures.length; if (currentFrame < 0) { currentFrame += this._textures.length; } return currentFrame; }; Object.defineProperties( AnimatedSprite.prototype, prototypeAccessors ); return AnimatedSprite; }(sprite.Sprite)); /** * @memberof PIXI.AnimatedSprite * @typedef {object} FrameObject * @type {object} * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame * @property {number} time - the duration of the frame in ms */ exports.AnimatedSprite = AnimatedSprite; },{"@pixi/core":7,"@pixi/sprite":34,"@pixi/ticker":38}],33:[function(require,module,exports){ /*! * @pixi/sprite-tiling - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/sprite-tiling is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var math = require('@pixi/math'); var utils = require('@pixi/utils'); var sprite = require('@pixi/sprite'); var constants = require('@pixi/constants'); var tempPoint = new math.Point(); /** * A tiling sprite is a fast way of rendering a tiling image * * @class * @extends PIXI.Sprite * @memberof PIXI */ var TilingSprite = /*@__PURE__*/(function (Sprite) { function TilingSprite(texture, width, height) { if ( width === void 0 ) width = 100; if ( height === void 0 ) height = 100; Sprite.call(this, texture); /** * Tile transform * * @member {PIXI.Transform} */ this.tileTransform = new math.Transform(); // /// private /** * The with of the tiling sprite * * @member {number} * @private */ this._width = width; /** * The height of the tiling sprite * * @member {number} * @private */ this._height = height; /** * Canvas pattern * * @type {CanvasPattern} * @private */ this._canvasPattern = null; /** * matrix that is applied to UV to get the coords in Texture normalized space to coords in BaseTexture space * * @member {PIXI.TextureMatrix} */ this.uvMatrix = texture.uvMatrix || new core.TextureMatrix(texture); /** * Plugin that is responsible for rendering this element. * Allows to customize the rendering process without overriding '_render' method. * * @member {string} * @default 'tilingSprite' */ this.pluginName = 'tilingSprite'; /** * Whether or not anchor affects uvs * * @member {boolean} * @default false */ this.uvRespectAnchor = false; } if ( Sprite ) TilingSprite.__proto__ = Sprite; TilingSprite.prototype = Object.create( Sprite && Sprite.prototype ); TilingSprite.prototype.constructor = TilingSprite; var prototypeAccessors = { clampMargin: { configurable: true },tileScale: { configurable: true },tilePosition: { configurable: true },width: { configurable: true },height: { configurable: true } }; /** * Changes frame clamping in corresponding textureTransform, shortcut * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas * * @default 0.5 * @member {number} */ prototypeAccessors.clampMargin.get = function () { return this.uvMatrix.clampMargin; }; prototypeAccessors.clampMargin.set = function (value) // eslint-disable-line require-jsdoc { this.uvMatrix.clampMargin = value; this.uvMatrix.update(true); }; /** * The scaling of the image that is being tiled * * @member {PIXI.ObservablePoint} */ prototypeAccessors.tileScale.get = function () { return this.tileTransform.scale; }; prototypeAccessors.tileScale.set = function (value) // eslint-disable-line require-jsdoc { this.tileTransform.scale.copyFrom(value); }; /** * The offset of the image that is being tiled * * @member {PIXI.ObservablePoint} */ prototypeAccessors.tilePosition.get = function () { return this.tileTransform.position; }; prototypeAccessors.tilePosition.set = function (value) // eslint-disable-line require-jsdoc { this.tileTransform.position.copyFrom(value); }; /** * @private */ TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate () { if (this.uvMatrix) { this.uvMatrix.texture = this._texture; } this._cachedTint = 0xFFFFFF; }; /** * Renders the object using the WebGL renderer * * @protected * @param {PIXI.Renderer} renderer - The renderer */ TilingSprite.prototype._render = function _render (renderer) { // tweak our texture temporarily.. var texture = this._texture; if (!texture || !texture.valid) { return; } this.tileTransform.updateLocalTransform(); this.uvMatrix.update(); renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); renderer.plugins[this.pluginName].render(this); }; /** * Updates the bounds of the tiling sprite. * * @protected */ TilingSprite.prototype._calculateBounds = function _calculateBounds () { var minX = this._width * -this._anchor._x; var minY = this._height * -this._anchor._y; var maxX = this._width * (1 - this._anchor._x); var maxY = this._height * (1 - this._anchor._y); this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); }; /** * Gets the local bounds of the sprite object. * * @param {PIXI.Rectangle} rect - The output rectangle. * @return {PIXI.Rectangle} The bounds. */ TilingSprite.prototype.getLocalBounds = function getLocalBounds (rect) { // we can do a fast local bounds if the sprite has no children! if (this.children.length === 0) { this._bounds.minX = this._width * -this._anchor._x; this._bounds.minY = this._height * -this._anchor._y; this._bounds.maxX = this._width * (1 - this._anchor._x); this._bounds.maxY = this._height * (1 - this._anchor._y); if (!rect) { if (!this._localBoundsRect) { this._localBoundsRect = new math.Rectangle(); } rect = this._localBoundsRect; } return this._bounds.getRectangle(rect); } return Sprite.prototype.getLocalBounds.call(this, rect); }; /** * Checks if a point is inside this tiling sprite. * * @param {PIXI.Point} point - the point to check * @return {boolean} Whether or not the sprite contains the point. */ TilingSprite.prototype.containsPoint = function containsPoint (point) { this.worldTransform.applyInverse(point, tempPoint); var width = this._width; var height = this._height; var x1 = -width * this.anchor._x; if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { var y1 = -height * this.anchor._y; if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { return true; } } return false; }; /** * Destroys this sprite and optionally its texture and children * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options * have been set to that value * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy * method called as well. 'options' will be passed on to those calls. * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well */ TilingSprite.prototype.destroy = function destroy (options) { Sprite.prototype.destroy.call(this, options); this.tileTransform = null; this.uvMatrix = null; }; /** * Helper function that creates a new tiling sprite based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * * @static * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from * @param {number} width - the width of the tiling sprite * @param {number} height - the height of the tiling sprite * @return {PIXI.TilingSprite} The newly created texture */ TilingSprite.from = function from (source, width, height) { return new TilingSprite(core.Texture.from(source), width, height); }; /** * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId * The frame ids are created when a Texture packer file has been loaded * * @static * @param {string} frameId - The frame Id of the texture in the cache * @param {number} width - the width of the tiling sprite * @param {number} height - the height of the tiling sprite * @return {PIXI.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId */ TilingSprite.fromFrame = function fromFrame (frameId, width, height) { var texture = utils.TextureCache[frameId]; if (!texture) { throw new Error(("The frameId \"" + frameId + "\" does not exist in the texture cache " + (this))); } return new TilingSprite(texture, width, height); }; /** * Helper function that creates a sprite that will contain a texture based on an image url * If the image is not in the texture cache it will be loaded * * @static * @param {string} imageId - The image url of the texture * @param {number} width - the width of the tiling sprite * @param {number} height - the height of the tiling sprite * @param {Object} [options] - See {@link PIXI.BaseTexture}'s constructor for options. * @return {PIXI.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id */ TilingSprite.fromImage = function fromImage (imageId, width, height, options) { // Fallback support for crossorigin, scaleMode parameters if (options && typeof options !== 'object') { options = { scaleMode: arguments[4], resourceOptions: { crossorigin: arguments[3], }, }; } return new TilingSprite(core.Texture.from(imageId, options), width, height); }; /** * The width of the sprite, setting this will actually modify the scale to achieve the value set * * @member {number} */ prototypeAccessors.width.get = function () { return this._width; }; prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc { this._width = value; }; /** * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set * * @member {number} */ prototypeAccessors.height.get = function () { return this._height; }; prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc { this._height = value; }; Object.defineProperties( TilingSprite.prototype, prototypeAccessors ); return TilingSprite; }(sprite.Sprite)); var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; var fragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord - floor(vTextureCoord - uClampOffset);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 texSample = texture2D(uSampler, coord);\n gl_FragColor = texSample * uColor;\n}\n"; var fragmentSimple = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n"; var tempMat = new math.Matrix(); /** * WebGL renderer plugin for tiling sprites * * @class * @memberof PIXI * @extends PIXI.ObjectRenderer */ var TilingSpriteRenderer = /*@__PURE__*/(function (ObjectRenderer) { function TilingSpriteRenderer(renderer) { ObjectRenderer.call(this, renderer); var uniforms = { globals: this.renderer.globalUniforms }; this.shader = core.Shader.from(vertex, fragment, uniforms); this.simpleShader = core.Shader.from(vertex, fragmentSimple, uniforms); this.quad = new core.QuadUv(); /** * The WebGL state in which this renderer will work. * * @member {PIXI.State} * @readonly */ this.state = core.State.for2d(); } if ( ObjectRenderer ) TilingSpriteRenderer.__proto__ = ObjectRenderer; TilingSpriteRenderer.prototype = Object.create( ObjectRenderer && ObjectRenderer.prototype ); TilingSpriteRenderer.prototype.constructor = TilingSpriteRenderer; /** * * @param {PIXI.TilingSprite} ts tilingSprite to be rendered */ TilingSpriteRenderer.prototype.render = function render (ts) { var renderer = this.renderer; var quad = this.quad; var vertices = quad.vertices; vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x; vertices[1] = vertices[3] = ts._height * -ts.anchor.y; vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x); vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); if (ts.uvRespectAnchor) { vertices = quad.uvs; vertices[0] = vertices[6] = -ts.anchor.x; vertices[1] = vertices[3] = -ts.anchor.y; vertices[2] = vertices[4] = 1.0 - ts.anchor.x; vertices[5] = vertices[7] = 1.0 - ts.anchor.y; } quad.invalidate(); var tex = ts._texture; var baseTex = tex.baseTexture; var lt = ts.tileTransform.localTransform; var uv = ts.uvMatrix; var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; // auto, force repeat wrapMode for big tiling textures if (isSimple) { if (!baseTex._glTextures[renderer.CONTEXT_UID]) { if (baseTex.wrapMode === constants.WRAP_MODES.CLAMP) { baseTex.wrapMode = constants.WRAP_MODES.REPEAT; } } else { isSimple = baseTex.wrapMode !== constants.WRAP_MODES.CLAMP; } } var shader = isSimple ? this.simpleShader : this.shader; var w = tex.width; var h = tex.height; var W = ts._width; var H = ts._height; tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); // that part is the same as above: // tempMat.identity(); // tempMat.scale(tex.width, tex.height); // tempMat.prepend(lt); // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); tempMat.invert(); if (isSimple) { tempMat.prepend(uv.mapCoord); } else { shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); shader.uniforms.uClampFrame = uv.uClampFrame; shader.uniforms.uClampOffset = uv.uClampOffset; } shader.uniforms.uTransform = tempMat.toArray(true); shader.uniforms.uColor = utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.alphaMode); shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); shader.uniforms.uSampler = tex; renderer.shader.bind(shader); renderer.geometry.bind(quad);// , renderer.shader.getGLShader()); this.state.blendMode = utils.correctBlendMode(ts.blendMode, baseTex.alphaMode); renderer.state.set(this.state); renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0); }; return TilingSpriteRenderer; }(core.ObjectRenderer)); exports.TilingSprite = TilingSprite; exports.TilingSpriteRenderer = TilingSpriteRenderer; },{"@pixi/constants":6,"@pixi/core":7,"@pixi/math":21,"@pixi/sprite":34,"@pixi/utils":39}],34:[function(require,module,exports){ /*! * @pixi/sprite - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/sprite is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var math = require('@pixi/math'); var utils = require('@pixi/utils'); var core = require('@pixi/core'); var constants = require('@pixi/constants'); var display = require('@pixi/display'); var settings = require('@pixi/settings'); var tempPoint = new math.Point(); var indices = new Uint16Array([0, 1, 2, 0, 2, 3]); /** * The Sprite object is the base for all textured objects that are rendered to the screen * * A sprite can be created directly from an image like this: * * ```js * let sprite = PIXI.Sprite.from('assets/image.png'); * ``` * * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}, * as swapping base textures when rendering to the screen is inefficient. * * ```js * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); * * function setup() { * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); * ... * } * ``` * * @class * @extends PIXI.Container * @memberof PIXI */ var Sprite = /*@__PURE__*/(function (Container) { function Sprite(texture) { Container.call(this); /** * The anchor point defines the normalized coordinates * in the texture that map to the position of this * sprite. * * By default, this is `(0,0)` (or `texture.defaultAnchor` * if you have modified that), which means the position * `(x,y)` of this `Sprite` will be the top-left corner. * * Note: Updating `texture.defaultAnchor` after * constructing a `Sprite` does _not_ update its anchor. * * {@link https://docs.cocos2d-x.org/cocos2d-x/en/sprites/manipulation.html} * * @default `texture.defaultAnchor` * @member {PIXI.ObservablePoint} * @private */ this._anchor = new math.ObservablePoint( this._onAnchorUpdate, this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0) ); /** * The texture that the sprite is using * * @private * @member {PIXI.Texture} */ this._texture = null; /** * The width of the sprite (this is initially set by the texture) * * @private * @member {number} */ this._width = 0; /** * The height of the sprite (this is initially set by the texture) * * @private * @member {number} */ this._height = 0; /** * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. * * @private * @member {number} * @default 0xFFFFFF */ this._tint = null; this._tintRGB = null; this.tint = 0xFFFFFF; /** * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. * * @member {number} * @default PIXI.BLEND_MODES.NORMAL * @see PIXI.BLEND_MODES */ this.blendMode = constants.BLEND_MODES.NORMAL; /** * The shader that will be used to render the sprite. Set to null to remove a current shader. * * @member {PIXI.Filter|PIXI.Shader} */ this.shader = null; /** * Cached tint value so we can tell when the tint is changed. * Value is used for 2d CanvasRenderer. * * @protected * @member {number} * @default 0xFFFFFF */ this._cachedTint = 0xFFFFFF; /** * this is used to store the uvs data of the sprite, assigned at the same time * as the vertexData in calculateVertices() * * @private * @member {Float32Array} */ this.uvs = null; // call texture setter this.texture = texture || core.Texture.EMPTY; /** * this is used to store the vertex data of the sprite (basically a quad) * * @private * @member {Float32Array} */ this.vertexData = new Float32Array(8); /** * This is used to calculate the bounds of the object IF it is a trimmed sprite * * @private * @member {Float32Array} */ this.vertexTrimmedData = null; this._transformID = -1; this._textureID = -1; this._transformTrimmedID = -1; this._textureTrimmedID = -1; // Batchable stuff.. // TODO could make this a mixin? this.indices = indices; this.size = 4; this.start = 0; /** * Plugin that is responsible for rendering this element. * Allows to customize the rendering process without overriding '_render' & '_renderCanvas' methods. * * @member {string} * @default 'batch' */ this.pluginName = 'batch'; /** * used to fast check if a sprite is.. a sprite! * @member {boolean} */ this.isSprite = true; /** * Internal roundPixels field * * @member {boolean} * @private */ this._roundPixels = settings.settings.ROUND_PIXELS; } if ( Container ) Sprite.__proto__ = Container; Sprite.prototype = Object.create( Container && Container.prototype ); Sprite.prototype.constructor = Sprite; var prototypeAccessors = { roundPixels: { configurable: true },width: { configurable: true },height: { configurable: true },anchor: { configurable: true },tint: { configurable: true },texture: { configurable: true } }; /** * When the texture is updated, this event will fire to update the scale and frame * * @private */ Sprite.prototype._onTextureUpdate = function _onTextureUpdate () { this._textureID = -1; this._textureTrimmedID = -1; this._cachedTint = 0xFFFFFF; // so if _width is 0 then width was not set.. if (this._width) { this.scale.x = utils.sign(this.scale.x) * this._width / this._texture.orig.width; } if (this._height) { this.scale.y = utils.sign(this.scale.y) * this._height / this._texture.orig.height; } }; /** * Called when the anchor position updates. * * @private */ Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate () { this._transformID = -1; this._transformTrimmedID = -1; }; /** * calculates worldTransform * vertices, store it in vertexData */ Sprite.prototype.calculateVertices = function calculateVertices () { var texture = this._texture; if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) { return; } // update texture UV here, because base texture can be changed without calling `_onTextureUpdate` if (this._textureID !== texture._updateID) { this.uvs = this._texture._uvs.uvsFloat32; } this._transformID = this.transform._worldID; this._textureID = texture._updateID; // set the vertex data var wt = this.transform.worldTransform; var a = wt.a; var b = wt.b; var c = wt.c; var d = wt.d; var tx = wt.tx; var ty = wt.ty; var vertexData = this.vertexData; var trim = texture.trim; var orig = texture.orig; var anchor = this._anchor; var w0 = 0; var w1 = 0; var h0 = 0; var h1 = 0; if (trim) { // if the sprite is trimmed and is not a tilingsprite then we need to add the extra // space before transforming the sprite coords. w1 = trim.x - (anchor._x * orig.width); w0 = w1 + trim.width; h1 = trim.y - (anchor._y * orig.height); h0 = h1 + trim.height; } else { w1 = -anchor._x * orig.width; w0 = w1 + orig.width; h1 = -anchor._y * orig.height; h0 = h1 + orig.height; } // xy vertexData[0] = (a * w1) + (c * h1) + tx; vertexData[1] = (d * h1) + (b * w1) + ty; // xy vertexData[2] = (a * w0) + (c * h1) + tx; vertexData[3] = (d * h1) + (b * w0) + ty; // xy vertexData[4] = (a * w0) + (c * h0) + tx; vertexData[5] = (d * h0) + (b * w0) + ty; // xy vertexData[6] = (a * w1) + (c * h0) + tx; vertexData[7] = (d * h0) + (b * w1) + ty; if (this._roundPixels) { var resolution = settings.settings.RESOLUTION; for (var i = 0; i < vertexData.length; ++i) { vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); } } }; /** * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData * This is used to ensure that the true width and height of a trimmed texture is respected */ Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices () { if (!this.vertexTrimmedData) { this.vertexTrimmedData = new Float32Array(8); } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { return; } this._transformTrimmedID = this.transform._worldID; this._textureTrimmedID = this._texture._updateID; // lets do some special trim code! var texture = this._texture; var vertexData = this.vertexTrimmedData; var orig = texture.orig; var anchor = this._anchor; // lets calculate the new untrimmed bounds.. var wt = this.transform.worldTransform; var a = wt.a; var b = wt.b; var c = wt.c; var d = wt.d; var tx = wt.tx; var ty = wt.ty; var w1 = -anchor._x * orig.width; var w0 = w1 + orig.width; var h1 = -anchor._y * orig.height; var h0 = h1 + orig.height; // xy vertexData[0] = (a * w1) + (c * h1) + tx; vertexData[1] = (d * h1) + (b * w1) + ty; // xy vertexData[2] = (a * w0) + (c * h1) + tx; vertexData[3] = (d * h1) + (b * w0) + ty; // xy vertexData[4] = (a * w0) + (c * h0) + tx; vertexData[5] = (d * h0) + (b * w0) + ty; // xy vertexData[6] = (a * w1) + (c * h0) + tx; vertexData[7] = (d * h0) + (b * w1) + ty; }; /** * * Renders the object using the WebGL renderer * * @protected * @param {PIXI.Renderer} renderer - The webgl renderer to use. */ Sprite.prototype._render = function _render (renderer) { this.calculateVertices(); renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); renderer.plugins[this.pluginName].render(this); }; /** * Updates the bounds of the sprite. * * @protected */ Sprite.prototype._calculateBounds = function _calculateBounds () { var trim = this._texture.trim; var orig = this._texture.orig; // First lets check to see if the current texture has a trim.. if (!trim || (trim.width === orig.width && trim.height === orig.height)) { // no trim! lets use the usual calculations.. this.calculateVertices(); this._bounds.addQuad(this.vertexData); } else { // lets calculate a special trimmed bounds... this.calculateTrimmedVertices(); this._bounds.addQuad(this.vertexTrimmedData); } }; /** * Gets the local bounds of the sprite object. * * @param {PIXI.Rectangle} [rect] - The output rectangle. * @return {PIXI.Rectangle} The bounds. */ Sprite.prototype.getLocalBounds = function getLocalBounds (rect) { // we can do a fast local bounds if the sprite has no children! if (this.children.length === 0) { this._bounds.minX = this._texture.orig.width * -this._anchor._x; this._bounds.minY = this._texture.orig.height * -this._anchor._y; this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y); if (!rect) { if (!this._localBoundsRect) { this._localBoundsRect = new math.Rectangle(); } rect = this._localBoundsRect; } return this._bounds.getRectangle(rect); } return Container.prototype.getLocalBounds.call(this, rect); }; /** * Tests if a point is inside this sprite * * @param {PIXI.Point} point - the point to test * @return {boolean} the result of the test */ Sprite.prototype.containsPoint = function containsPoint (point) { this.worldTransform.applyInverse(point, tempPoint); var width = this._texture.orig.width; var height = this._texture.orig.height; var x1 = -width * this.anchor.x; var y1 = 0; if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { y1 = -height * this.anchor.y; if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { return true; } } return false; }; /** * Destroys this sprite and optionally its texture and children * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options * have been set to that value * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy * method called as well. 'options' will be passed on to those calls. * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well */ Sprite.prototype.destroy = function destroy (options) { Container.prototype.destroy.call(this, options); this._texture.off('update', this._onTextureUpdate, this); this._anchor = null; var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; if (destroyTexture) { var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; this._texture.destroy(!!destroyBaseTexture); } this._texture = null; this.shader = null; }; // some helper functions.. /** * Helper function that creates a new sprite based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * * @static * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. * @return {PIXI.Sprite} The newly created sprite */ Sprite.from = function from (source, options) { var texture = (source instanceof core.Texture) ? source : core.Texture.from(source, options); return new Sprite(texture); }; /** * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. * Advantages can include sharper image quality (like text) and faster rendering on canvas. * The main disadvantage is movement of objects may appear less smooth. * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} * * @member {boolean} * @default false */ prototypeAccessors.roundPixels.set = function (value) { if (this._roundPixels !== value) { this._transformID = -1; } this._roundPixels = value; }; prototypeAccessors.roundPixels.get = function () { return this._roundPixels; }; /** * The width of the sprite, setting this will actually modify the scale to achieve the value set * * @member {number} */ prototypeAccessors.width.get = function () { return Math.abs(this.scale.x) * this._texture.orig.width; }; prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc { var s = utils.sign(this.scale.x) || 1; this.scale.x = s * value / this._texture.orig.width; this._width = value; }; /** * The height of the sprite, setting this will actually modify the scale to achieve the value set * * @member {number} */ prototypeAccessors.height.get = function () { return Math.abs(this.scale.y) * this._texture.orig.height; }; prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc { var s = utils.sign(this.scale.y) || 1; this.scale.y = s * value / this._texture.orig.height; this._height = value; }; /** * The anchor sets the origin point of the text. The default value is taken from the {@link PIXI.Texture|Texture} * and passed to the constructor. * * The default is `(0,0)`, this means the text's origin is the top left. * * Setting the anchor to `(0.5,0.5)` means the text's origin is centered. * * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner. * * If you pass only single parameter, it will set both x and y to the same value as shown in the example below. * * @example * const sprite = new PIXI.Sprite(texture); * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5). * * @member {PIXI.ObservablePoint} */ prototypeAccessors.anchor.get = function () { return this._anchor; }; prototypeAccessors.anchor.set = function (value) // eslint-disable-line require-jsdoc { this._anchor.copyFrom(value); }; /** * The tint applied to the sprite. This is a hex value. * A value of 0xFFFFFF will remove any tint effect. * * @member {number} * @default 0xFFFFFF */ prototypeAccessors.tint.get = function () { return this._tint; }; prototypeAccessors.tint.set = function (value) // eslint-disable-line require-jsdoc { this._tint = value; this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); }; /** * The texture that the sprite is using * * @member {PIXI.Texture} */ prototypeAccessors.texture.get = function () { return this._texture; }; prototypeAccessors.texture.set = function (value) // eslint-disable-line require-jsdoc { if (this._texture === value) { return; } if (this._texture) { this._texture.off('update', this._onTextureUpdate, this); } this._texture = value || core.Texture.EMPTY; this._cachedTint = 0xFFFFFF; this._textureID = -1; this._textureTrimmedID = -1; if (value) { // wait for the texture to load if (value.baseTexture.valid) { this._onTextureUpdate(); } else { value.once('update', this._onTextureUpdate, this); } } }; Object.defineProperties( Sprite.prototype, prototypeAccessors ); return Sprite; }(display.Container)); exports.Sprite = Sprite; },{"@pixi/constants":6,"@pixi/core":7,"@pixi/display":8,"@pixi/math":21,"@pixi/settings":31,"@pixi/utils":39}],35:[function(require,module,exports){ /*! * @pixi/spritesheet - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/spritesheet is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var math = require('@pixi/math'); var core = require('@pixi/core'); var utils = require('@pixi/utils'); var loaders = require('@pixi/loaders'); /** * Utility class for maintaining reference to a collection * of Textures on a single Spritesheet. * * To access a sprite sheet from your code pass its JSON data file to Pixi's loader: * * ```js * PIXI.Loader.shared.add("images/spritesheet.json").load(setup); * * function setup() { * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet; * ... * } * ``` * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. * * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only * supported by TexturePacker. * * @class * @memberof PIXI */ var Spritesheet = function Spritesheet(baseTexture, data, resolutionFilename) { if ( resolutionFilename === void 0 ) resolutionFilename = null; /** * Reference to ths source texture * @type {PIXI.BaseTexture} */ this.baseTexture = baseTexture; /** * A map containing all textures of the sprite sheet. * Can be used to create a {@link PIXI.Sprite|Sprite}: * ```js * new PIXI.Sprite(sheet.textures["image.png"]); * ``` * @member {Object} */ this.textures = {}; /** * A map containing the textures for each animation. * Can be used to create an {@link PIXI.AnimatedSprite|AnimatedSprite}: * ```js * new PIXI.AnimatedSprite(sheet.animations["anim_name"]) * ``` * @member {Object} */ this.animations = {}; /** * Reference to the original JSON data. * @type {Object} */ this.data = data; /** * The resolution of the spritesheet. * @type {number} */ this.resolution = this._updateResolution( resolutionFilename || (this.baseTexture.resource ? this.baseTexture.resource.url : null) ); /** * Map of spritesheet frames. * @type {Object} * @private */ this._frames = this.data.frames; /** * Collection of frame names. * @type {string[]} * @private */ this._frameKeys = Object.keys(this._frames); /** * Current batch index being processed. * @type {number} * @private */ this._batchIndex = 0; /** * Callback when parse is completed. * @type {Function} * @private */ this._callback = null; }; var staticAccessors = { BATCH_SIZE: { configurable: true } }; /** * Generate the resolution from the filename or fallback * to the meta.scale field of the JSON data. * * @private * @param {string} resolutionFilename - The filename to use for resolving * the default resolution. * @return {number} Resolution to use for spritesheet. */ staticAccessors.BATCH_SIZE.get = function () { return 1000; }; Spritesheet.prototype._updateResolution = function _updateResolution (resolutionFilename) { var scale = this.data.meta.scale; // Use a defaultValue of `null` to check if a url-based resolution is set var resolution = utils.getResolutionOfUrl(resolutionFilename, null); // No resolution found via URL if (resolution === null) { // Use the scale value or default to 1 resolution = scale !== undefined ? parseFloat(scale) : 1; } // For non-1 resolutions, update baseTexture if (resolution !== 1) { this.baseTexture.setResolution(resolution); } return resolution; }; /** * Parser spritesheet from loaded data. This is done asynchronously * to prevent creating too many Texture within a single process. * * @param {Function} callback - Callback when complete returns * a map of the Textures for this spritesheet. */ Spritesheet.prototype.parse = function parse (callback) { this._batchIndex = 0; this._callback = callback; if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { this._processFrames(0); this._processAnimations(); this._parseComplete(); } else { this._nextBatch(); } }; /** * Process a batch of frames * * @private * @param {number} initialFrameIndex - The index of frame to start. */ Spritesheet.prototype._processFrames = function _processFrames (initialFrameIndex) { var frameIndex = initialFrameIndex; var maxFrames = Spritesheet.BATCH_SIZE; while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { var i = this._frameKeys[frameIndex]; var data = this._frames[i]; var rect = data.frame; if (rect) { var frame = null; var trim = null; var sourceSize = data.trimmed !== false && data.sourceSize ? data.sourceSize : data.frame; var orig = new math.Rectangle( 0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution ); if (data.rotated) { frame = new math.Rectangle( Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution ); } else { frame = new math.Rectangle( Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution ); } // Check to see if the sprite is trimmed if (data.trimmed !== false && data.spriteSourceSize) { trim = new math.Rectangle( Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution ); } this.textures[i] = new core.Texture( this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor ); // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions core.Texture.addToCache(this.textures[i], i); } frameIndex++; } }; /** * Parse animations config * * @private */ Spritesheet.prototype._processAnimations = function _processAnimations () { var animations = this.data.animations || {}; for (var animName in animations) { this.animations[animName] = []; for (var i = 0; i < animations[animName].length; i++) { var frameName = animations[animName][i]; this.animations[animName].push(this.textures[frameName]); } } }; /** * The parse has completed. * * @private */ Spritesheet.prototype._parseComplete = function _parseComplete () { var callback = this._callback; this._callback = null; this._batchIndex = 0; callback.call(this, this.textures); }; /** * Begin the next batch of textures. * * @private */ Spritesheet.prototype._nextBatch = function _nextBatch () { var this$1 = this; this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); this._batchIndex++; setTimeout(function () { if (this$1._batchIndex * Spritesheet.BATCH_SIZE < this$1._frameKeys.length) { this$1._nextBatch(); } else { this$1._processAnimations(); this$1._parseComplete(); } }, 0); }; /** * Destroy Spritesheet and don't use after this. * * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well */ Spritesheet.prototype.destroy = function destroy (destroyBase) { if ( destroyBase === void 0 ) destroyBase = false; for (var i in this.textures) { this.textures[i].destroy(); } this._frames = null; this._frameKeys = null; this.data = null; this.textures = null; if (destroyBase) { this.baseTexture.destroy(); } this.baseTexture = null; }; Object.defineProperties( Spritesheet, staticAccessors ); /** * {@link PIXI.Loader Loader} middleware for loading texture atlases that have been created with * TexturePacker or similar JSON-based spritesheet. * * This middleware automatically generates Texture resources. * * @class * @memberof PIXI * @implements PIXI.ILoaderPlugin */ var SpritesheetLoader = function SpritesheetLoader () {}; SpritesheetLoader.use = function use (resource, next) { var imageResourceName = (resource.name) + "_image"; // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists if (!resource.data || resource.type !== loaders.LoaderResource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName] ) { next(); return; } var loadOptions = { crossOrigin: resource.crossOrigin, metadata: resource.metadata.imageMetadata, parentResource: resource, }; var resourcePath = SpritesheetLoader.getResourcePath(resource, this.baseUrl); // load the image for this sheet this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { if (res.error) { next(res.error); return; } var spritesheet = new Spritesheet( res.texture.baseTexture, resource.data, resource.url ); spritesheet.parse(function () { resource.spritesheet = spritesheet; resource.textures = spritesheet.textures; next(); }); }); }; /** * Get the spritesheets root path * @param {PIXI.LoaderResource} resource - Resource to check path * @param {string} baseUrl - Base root url */ SpritesheetLoader.getResourcePath = function getResourcePath (resource, baseUrl) { // Prepend url path unless the resource image is a data url if (resource.isDataUrl) { return resource.data.meta.image; } return utils.url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); }; exports.Spritesheet = Spritesheet; exports.SpritesheetLoader = SpritesheetLoader; },{"@pixi/core":7,"@pixi/loaders":20,"@pixi/math":21,"@pixi/utils":39}],36:[function(require,module,exports){ /*! * @pixi/text-bitmap - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/text-bitmap is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var core = require('@pixi/core'); var display = require('@pixi/display'); var math = require('@pixi/math'); var settings = require('@pixi/settings'); var sprite = require('@pixi/sprite'); var utils = require('@pixi/utils'); var loaders = require('@pixi/loaders'); /** * A BitmapText object will create a line or multiple lines of text using bitmap font. * * The primary advantage of this class over Text is that all of your textures are pre-generated and loading, * meaning that rendering is fast, and changing text has no performance implications. * * The primary disadvantage is that you need to preload the bitmap font assets, and thus the styling is set in stone. * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters. * * To split a line you can use '\n', '\r' or '\r\n' in your string. * * You can generate the fnt files using * http://www.angelcode.com/products/bmfont/ for Windows or * http://www.bmglyph.com/ for Mac. * * A BitmapText can only be created when the font is loaded. * * ```js * // in this case the font is in a file called 'desyrel.fnt' * let bitmapText = new PIXI.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); * ``` * * @class * @extends PIXI.Container * @memberof PIXI */ var BitmapText = /*@__PURE__*/(function (Container) { function BitmapText(text, style) { var this$1 = this; if ( style === void 0 ) style = {}; Container.call(this); /** * Private tracker for the width of the overall text * * @member {number} * @private */ this._textWidth = 0; /** * Private tracker for the height of the overall text * * @member {number} * @private */ this._textHeight = 0; /** * Private tracker for the letter sprite pool. * * @member {PIXI.Sprite[]} * @private */ this._glyphs = []; /** * Private tracker for the current style. * * @member {object} * @private */ this._font = { tint: style.tint !== undefined ? style.tint : 0xFFFFFF, align: style.align || 'left', name: null, size: 0, }; /** * Private tracker for the current font. * * @member {object} * @private */ this.font = style.font; // run font setter /** * Private tracker for the current text. * * @member {string} * @private */ this._text = text; /** * The max width of this bitmap text in pixels. If the text provided is longer than the * value provided, line breaks will be automatically inserted in the last whitespace. * Disable by setting value to 0 * * @member {number} * @private */ this._maxWidth = 0; /** * The max line height. This is useful when trying to use the total height of the Text, * ie: when trying to vertically align. * * @member {number} * @private */ this._maxLineHeight = 0; /** * Letter spacing. This is useful for setting the space between characters. * @member {number} * @private */ this._letterSpacing = 0; /** * Text anchor. read-only * * @member {PIXI.ObservablePoint} * @private */ this._anchor = new math.ObservablePoint(function () { this$1.dirty = true; }, this, 0, 0); /** * The dirty state of this object. * * @member {boolean} */ this.dirty = false; /** * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. * Advantages can include sharper image quality (like text) and faster rendering on canvas. * The main disadvantage is movement of objects may appear less smooth. * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} * * @member {boolean} * @default false */ this.roundPixels = settings.settings.ROUND_PIXELS; this.updateText(); } if ( Container ) BitmapText.__proto__ = Container; BitmapText.prototype = Object.create( Container && Container.prototype ); BitmapText.prototype.constructor = BitmapText; var prototypeAccessors = { tint: { configurable: true },align: { configurable: true },anchor: { configurable: true },font: { configurable: true },text: { configurable: true },maxWidth: { configurable: true },maxLineHeight: { configurable: true },textWidth: { configurable: true },letterSpacing: { configurable: true },textHeight: { configurable: true } }; /** * Renders text and updates it when needed * * @private */ BitmapText.prototype.updateText = function updateText () { var data = BitmapText.fonts[this._font.name]; var scale = this._font.size / data.size; var pos = new math.Point(); var chars = []; var lineWidths = []; var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' '; var textLength = text.length; var maxWidth = this._maxWidth * data.size / this._font.size; var prevCharCode = null; var lastLineWidth = 0; var maxLineWidth = 0; var line = 0; var lastBreakPos = -1; var lastBreakWidth = 0; var spacesRemoved = 0; var maxLineHeight = 0; for (var i = 0; i < textLength; i++) { var charCode = text.charCodeAt(i); var char = text.charAt(i); if ((/(?:\s)/).test(char)) { lastBreakPos = i; lastBreakWidth = lastLineWidth; } if (char === '\r' || char === '\n') { lineWidths.push(lastLineWidth); maxLineWidth = Math.max(maxLineWidth, lastLineWidth); ++line; ++spacesRemoved; pos.x = 0; pos.y += data.lineHeight; prevCharCode = null; continue; } var charData = data.chars[charCode]; if (!charData) { continue; } if (prevCharCode && charData.kerning[prevCharCode]) { pos.x += charData.kerning[prevCharCode]; } chars.push({ texture: charData.texture, line: line, charCode: charCode, position: new math.Point(pos.x + charData.xOffset + (this._letterSpacing / 2), pos.y + charData.yOffset), }); pos.x += charData.xAdvance + this._letterSpacing; lastLineWidth = pos.x; maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height)); prevCharCode = charCode; if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { ++spacesRemoved; utils.removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); i = lastBreakPos; lastBreakPos = -1; lineWidths.push(lastBreakWidth); maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); line++; pos.x = 0; pos.y += data.lineHeight; prevCharCode = null; } } var lastChar = text.charAt(text.length - 1); if (lastChar !== '\r' && lastChar !== '\n') { if ((/(?:\s)/).test(lastChar)) { lastLineWidth = lastBreakWidth; } lineWidths.push(lastLineWidth); maxLineWidth = Math.max(maxLineWidth, lastLineWidth); } var lineAlignOffsets = []; for (var i$1 = 0; i$1 <= line; i$1++) { var alignOffset = 0; if (this._font.align === 'right') { alignOffset = maxLineWidth - lineWidths[i$1]; } else if (this._font.align === 'center') { alignOffset = (maxLineWidth - lineWidths[i$1]) / 2; } lineAlignOffsets.push(alignOffset); } var lenChars = chars.length; var tint = this.tint; for (var i$2 = 0; i$2 < lenChars; i$2++) { var c = this._glyphs[i$2]; // get the next glyph sprite if (c) { c.texture = chars[i$2].texture; } else { c = new sprite.Sprite(chars[i$2].texture); c.roundPixels = this.roundPixels; this._glyphs.push(c); } c.position.x = (chars[i$2].position.x + lineAlignOffsets[chars[i$2].line]) * scale; c.position.y = chars[i$2].position.y * scale; c.scale.x = c.scale.y = scale; c.tint = tint; if (!c.parent) { this.addChild(c); } } // remove unnecessary children. for (var i$3 = lenChars; i$3 < this._glyphs.length; ++i$3) { this.removeChild(this._glyphs[i$3]); } this._textWidth = maxLineWidth * scale; this._textHeight = (pos.y + data.lineHeight) * scale; // apply anchor if (this.anchor.x !== 0 || this.anchor.y !== 0) { for (var i$4 = 0; i$4 < lenChars; i$4++) { this._glyphs[i$4].x -= this._textWidth * this.anchor.x; this._glyphs[i$4].y -= this._textHeight * this.anchor.y; } } this._maxLineHeight = maxLineHeight * scale; }; /** * Updates the transform of this object * * @private */ BitmapText.prototype.updateTransform = function updateTransform () { this.validate(); this.containerUpdateTransform(); }; /** * Validates text before calling parent's getLocalBounds * * @return {PIXI.Rectangle} The rectangular bounding area */ BitmapText.prototype.getLocalBounds = function getLocalBounds () { this.validate(); return Container.prototype.getLocalBounds.call(this); }; /** * Updates text when needed * * @private */ BitmapText.prototype.validate = function validate () { if (this.dirty) { this.updateText(); this.dirty = false; } }; /** * The tint of the BitmapText object. * * @member {number} */ prototypeAccessors.tint.get = function () { return this._font.tint; }; prototypeAccessors.tint.set = function (value) // eslint-disable-line require-jsdoc { this._font.tint = (typeof value === 'number' && value >= 0) ? value : 0xFFFFFF; this.dirty = true; }; /** * The alignment of the BitmapText object. * * @member {string} * @default 'left' */ prototypeAccessors.align.get = function () { return this._font.align; }; prototypeAccessors.align.set = function (value) // eslint-disable-line require-jsdoc { this._font.align = value || 'left'; this.dirty = true; }; /** * The anchor sets the origin point of the text. * * The default is `(0,0)`, this means the text's origin is the top left. * * Setting the anchor to `(0.5,0.5)` means the text's origin is centered. * * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner. * * @member {PIXI.Point | number} */ prototypeAccessors.anchor.get = function () { return this._anchor; }; prototypeAccessors.anchor.set = function (value) // eslint-disable-line require-jsdoc { if (typeof value === 'number') { this._anchor.set(value); } else { this._anchor.copyFrom(value); } }; /** * The font descriptor of the BitmapText object. * * @member {object} */ prototypeAccessors.font.get = function () { return this._font; }; prototypeAccessors.font.set = function (value) // eslint-disable-line require-jsdoc { if (!value) { return; } if (typeof value === 'string') { value = value.split(' '); this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; } else { this._font.name = value.name; this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); } this.dirty = true; }; /** * The text of the BitmapText object. * * @member {string} */ prototypeAccessors.text.get = function () { return this._text; }; prototypeAccessors.text.set = function (text) // eslint-disable-line require-jsdoc { text = String(text === null || text === undefined ? '' : text); if (this._text === text) { return; } this._text = text; this.dirty = true; }; /** * The max width of this bitmap text in pixels. If the text provided is longer than the * value provided, line breaks will be automatically inserted in the last whitespace. * Disable by setting the value to 0. * * @member {number} */ prototypeAccessors.maxWidth.get = function () { return this._maxWidth; }; prototypeAccessors.maxWidth.set = function (value) // eslint-disable-line require-jsdoc { if (this._maxWidth === value) { return; } this._maxWidth = value; this.dirty = true; }; /** * The max line height. This is useful when trying to use the total height of the Text, * i.e. when trying to vertically align. * * @member {number} * @readonly */ prototypeAccessors.maxLineHeight.get = function () { this.validate(); return this._maxLineHeight; }; /** * The width of the overall text, different from fontSize, * which is defined in the style object. * * @member {number} * @readonly */ prototypeAccessors.textWidth.get = function () { this.validate(); return this._textWidth; }; /** * Additional space between characters. * * @member {number} */ prototypeAccessors.letterSpacing.get = function () { return this._letterSpacing; }; prototypeAccessors.letterSpacing.set = function (value) // eslint-disable-line require-jsdoc { if (this._letterSpacing !== value) { this._letterSpacing = value; this.dirty = true; } }; /** * The height of the overall text, different from fontSize, * which is defined in the style object. * * @member {number} * @readonly */ prototypeAccessors.textHeight.get = function () { this.validate(); return this._textHeight; }; /** * Register a bitmap font with data and a texture. * * @static * @param {XMLDocument} xml - The XML document data. * @param {Object.|PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page. * If providing an object, the key is the `` element's `file` attribute in the FNT file. * @return {Object} Result font object with font, size, lineHeight and char fields. */ BitmapText.registerFont = function registerFont (xml, textures) { var data = {}; var info = xml.getElementsByTagName('info')[0]; var common = xml.getElementsByTagName('common')[0]; var pages = xml.getElementsByTagName('page'); var res = utils.getResolutionOfUrl(pages[0].getAttribute('file'), settings.settings.RESOLUTION); var pagesTextures = {}; data.font = info.getAttribute('face'); data.size = parseInt(info.getAttribute('size'), 10); data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res; data.chars = {}; // Single texture, convert to list if (textures instanceof core.Texture) { textures = [textures]; } // Convert the input Texture, Textures or object // into a page Texture lookup by "id" for (var i = 0; i < pages.length; i++) { var id = pages[i].getAttribute('id'); var file = pages[i].getAttribute('file'); pagesTextures[id] = textures instanceof Array ? textures[i] : textures[file]; } // parse letters var letters = xml.getElementsByTagName('char'); for (var i$1 = 0; i$1 < letters.length; i$1++) { var letter = letters[i$1]; var charCode = parseInt(letter.getAttribute('id'), 10); var page = letter.getAttribute('page') || 0; var textureRect = new math.Rectangle( (parseInt(letter.getAttribute('x'), 10) / res) + (pagesTextures[page].frame.x / res), (parseInt(letter.getAttribute('y'), 10) / res) + (pagesTextures[page].frame.y / res), parseInt(letter.getAttribute('width'), 10) / res, parseInt(letter.getAttribute('height'), 10) / res ); data.chars[charCode] = { xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res, yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res, xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res, kerning: {}, texture: new core.Texture(pagesTextures[page].baseTexture, textureRect), page: page, }; } // parse kernings var kernings = xml.getElementsByTagName('kerning'); for (var i$2 = 0; i$2 < kernings.length; i$2++) { var kerning = kernings[i$2]; var first = parseInt(kerning.getAttribute('first'), 10) / res; var second = parseInt(kerning.getAttribute('second'), 10) / res; var amount = parseInt(kerning.getAttribute('amount'), 10) / res; if (data.chars[second]) { data.chars[second].kerning[first] = amount; } } // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 // but it's very likely to change BitmapText.fonts[data.font] = data; return data; }; Object.defineProperties( BitmapText.prototype, prototypeAccessors ); return BitmapText; }(display.Container)); BitmapText.fonts = {}; /** * {@link PIXI.Loader Loader} middleware for loading * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}. * @class * @memberof PIXI * @implements PIXI.ILoaderPlugin */ var BitmapFontLoader = function BitmapFontLoader () {}; BitmapFontLoader.parse = function parse (resource, texture) { resource.bitmapFont = BitmapText.registerFont(resource.data, texture); }; /** * Called when the plugin is installed. * * @see PIXI.Loader.registerPlugin */ BitmapFontLoader.add = function add () { loaders.LoaderResource.setExtensionXhrType('fnt', loaders.LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT); }; /** * Replacement for NodeJS's path.dirname * @private * @param {string} url Path to get directory for */ BitmapFontLoader.dirname = function dirname (url) { var dir = url .replace(/\\/g, '/') // convert windows notation to UNIX notation, URL-safe because it's a forbidden character .replace(/\/$/, '') // replace trailing slash .replace(/\/[^\/]*$/, ''); // remove everything after the last // File request is relative, use current directory if (dir === url) { return '.'; } // Started with a slash else if (dir === '') { return '/'; } return dir; }; /** * Called after a resource is loaded. * @see PIXI.Loader.loaderMiddleware * @param {PIXI.LoaderResource} resource * @param {function} next */ BitmapFontLoader.use = function use (resource, next) { // skip if no data or not xml data if (!resource.data || resource.type !== loaders.LoaderResource.TYPE.XML) { next(); return; } // skip if not bitmap font data, using some silly duck-typing if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null ) { next(); return; } var xmlUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : ''; if (resource.isDataUrl) { if (xmlUrl === '.') { xmlUrl = ''; } if (this.baseUrl && xmlUrl) { // if baseurl has a trailing slash then add one to xmlUrl so the replace works below if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { xmlUrl += '/'; } } } // remove baseUrl from xmlUrl xmlUrl = xmlUrl.replace(this.baseUrl, ''); // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { xmlUrl += '/'; } var pages = resource.data.getElementsByTagName('page'); var textures = {}; // Handle completed, when the number of textures // load is the same number as references in the fnt file var completed = function (page) { textures[page.metadata.pageFile] = page.texture; if (Object.keys(textures).length === pages.length) { BitmapFontLoader.parse(resource, textures); next(); } }; for (var i = 0; i < pages.length; ++i) { var pageFile = pages[i].getAttribute('file'); var url = xmlUrl + pageFile; var exists = false; // incase the image is loaded outside // using the same loader, resource will be available for (var name in this.resources) { var bitmapResource = this.resources[name]; if (bitmapResource.url === url) { bitmapResource.metadata.pageFile = pageFile; if (bitmapResource.texture) { completed(bitmapResource); } else { bitmapResource.onAfterMiddleware.add(completed); } exists = true; break; } } // texture is not loaded, we'll attempt to add // it to the load and add the texture to the list if (!exists) { // Standard loading options for images var options = { crossOrigin: resource.crossOrigin, loadType: loaders.LoaderResource.LOAD_TYPE.IMAGE, metadata: Object.assign( { pageFile: pageFile }, resource.metadata.imageMetadata ), parentResource: resource, }; this.add(url, options, completed); } } }; exports.BitmapFontLoader = BitmapFontLoader; exports.BitmapText = BitmapText; },{"@pixi/core":7,"@pixi/display":8,"@pixi/loaders":20,"@pixi/math":21,"@pixi/settings":31,"@pixi/sprite":34,"@pixi/utils":39}],37:[function(require,module,exports){ /*! * @pixi/text - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/text is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var sprite = require('@pixi/sprite'); var core = require('@pixi/core'); var settings = require('@pixi/settings'); var math = require('@pixi/math'); var utils = require('@pixi/utils'); /** * Constants that define the type of gradient on text. * * @static * @constant * @name TEXT_GRADIENT * @memberof PIXI * @type {object} * @property {number} LINEAR_VERTICAL Vertical gradient * @property {number} LINEAR_HORIZONTAL Linear gradient */ var TEXT_GRADIENT = { LINEAR_VERTICAL: 0, LINEAR_HORIZONTAL: 1, }; // disabling eslint for now, going to rewrite this in v5 var defaultStyle = { align: 'left', breakWords: false, dropShadow: false, dropShadowAlpha: 1, dropShadowAngle: Math.PI / 6, dropShadowBlur: 0, dropShadowColor: 'black', dropShadowDistance: 5, fill: 'black', fillGradientType: TEXT_GRADIENT.LINEAR_VERTICAL, fillGradientStops: [], fontFamily: 'Arial', fontSize: 26, fontStyle: 'normal', fontVariant: 'normal', fontWeight: 'normal', letterSpacing: 0, lineHeight: 0, lineJoin: 'miter', miterLimit: 10, padding: 0, stroke: 'black', strokeThickness: 0, textBaseline: 'alphabetic', trim: false, whiteSpace: 'pre', wordWrap: false, wordWrapWidth: 100, leading: 0, }; var genericFontFamilies = [ 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui' ]; /** * A TextStyle Object contains information to decorate a Text objects. * * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it. * * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style). * * @class * @memberof PIXI */ var TextStyle = function TextStyle(style) { this.styleID = 0; this.reset(); deepCopyProperties(this, style, style); }; var prototypeAccessors = { align: { configurable: true },breakWords: { configurable: true },dropShadow: { configurable: true },dropShadowAlpha: { configurable: true },dropShadowAngle: { configurable: true },dropShadowBlur: { configurable: true },dropShadowColor: { configurable: true },dropShadowDistance: { configurable: true },fill: { configurable: true },fillGradientType: { configurable: true },fillGradientStops: { configurable: true },fontFamily: { configurable: true },fontSize: { configurable: true },fontStyle: { configurable: true },fontVariant: { configurable: true },fontWeight: { configurable: true },letterSpacing: { configurable: true },lineHeight: { configurable: true },leading: { configurable: true },lineJoin: { configurable: true },miterLimit: { configurable: true },padding: { configurable: true },stroke: { configurable: true },strokeThickness: { configurable: true },textBaseline: { configurable: true },trim: { configurable: true },whiteSpace: { configurable: true },wordWrap: { configurable: true },wordWrapWidth: { configurable: true } }; /** * Creates a new TextStyle object with the same values as this one. * Note that the only the properties of the object are cloned. * * @return {PIXI.TextStyle} New cloned TextStyle object */ TextStyle.prototype.clone = function clone () { var clonedProperties = {}; deepCopyProperties(clonedProperties, this, defaultStyle); return new TextStyle(clonedProperties); }; /** * Resets all properties to the defaults specified in TextStyle.prototype._default */ TextStyle.prototype.reset = function reset () { deepCopyProperties(this, defaultStyle, defaultStyle); }; /** * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text * * @member {string} */ prototypeAccessors.align.get = function () { return this._align; }; prototypeAccessors.align.set = function (align) // eslint-disable-line require-jsdoc { if (this._align !== align) { this._align = align; this.styleID++; } }; /** * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true * * @member {boolean} */ prototypeAccessors.breakWords.get = function () { return this._breakWords; }; prototypeAccessors.breakWords.set = function (breakWords) // eslint-disable-line require-jsdoc { if (this._breakWords !== breakWords) { this._breakWords = breakWords; this.styleID++; } }; /** * Set a drop shadow for the text * * @member {boolean} */ prototypeAccessors.dropShadow.get = function () { return this._dropShadow; }; prototypeAccessors.dropShadow.set = function (dropShadow) // eslint-disable-line require-jsdoc { if (this._dropShadow !== dropShadow) { this._dropShadow = dropShadow; this.styleID++; } }; /** * Set alpha for the drop shadow * * @member {number} */ prototypeAccessors.dropShadowAlpha.get = function () { return this._dropShadowAlpha; }; prototypeAccessors.dropShadowAlpha.set = function (dropShadowAlpha) // eslint-disable-line require-jsdoc { if (this._dropShadowAlpha !== dropShadowAlpha) { this._dropShadowAlpha = dropShadowAlpha; this.styleID++; } }; /** * Set a angle of the drop shadow * * @member {number} */ prototypeAccessors.dropShadowAngle.get = function () { return this._dropShadowAngle; }; prototypeAccessors.dropShadowAngle.set = function (dropShadowAngle) // eslint-disable-line require-jsdoc { if (this._dropShadowAngle !== dropShadowAngle) { this._dropShadowAngle = dropShadowAngle; this.styleID++; } }; /** * Set a shadow blur radius * * @member {number} */ prototypeAccessors.dropShadowBlur.get = function () { return this._dropShadowBlur; }; prototypeAccessors.dropShadowBlur.set = function (dropShadowBlur) // eslint-disable-line require-jsdoc { if (this._dropShadowBlur !== dropShadowBlur) { this._dropShadowBlur = dropShadowBlur; this.styleID++; } }; /** * A fill style to be used on the dropshadow e.g 'red', '#00FF00' * * @member {string|number} */ prototypeAccessors.dropShadowColor.get = function () { return this._dropShadowColor; }; prototypeAccessors.dropShadowColor.set = function (dropShadowColor) // eslint-disable-line require-jsdoc { var outputColor = getColor(dropShadowColor); if (this._dropShadowColor !== outputColor) { this._dropShadowColor = outputColor; this.styleID++; } }; /** * Set a distance of the drop shadow * * @member {number} */ prototypeAccessors.dropShadowDistance.get = function () { return this._dropShadowDistance; }; prototypeAccessors.dropShadowDistance.set = function (dropShadowDistance) // eslint-disable-line require-jsdoc { if (this._dropShadowDistance !== dropShadowDistance) { this._dropShadowDistance = dropShadowDistance; this.styleID++; } }; /** * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. * Can be an array to create a gradient eg ['#000000','#FFFFFF'] * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} * * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} */ prototypeAccessors.fill.get = function () { return this._fill; }; prototypeAccessors.fill.set = function (fill) // eslint-disable-line require-jsdoc { var outputColor = getColor(fill); if (this._fill !== outputColor) { this._fill = outputColor; this.styleID++; } }; /** * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. * See {@link PIXI.TEXT_GRADIENT} * * @member {number} */ prototypeAccessors.fillGradientType.get = function () { return this._fillGradientType; }; prototypeAccessors.fillGradientType.set = function (fillGradientType) // eslint-disable-line require-jsdoc { if (this._fillGradientType !== fillGradientType) { this._fillGradientType = fillGradientType; this.styleID++; } }; /** * If fill is an array of colours to create a gradient, this array can set the stop points * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. * * @member {number[]} */ prototypeAccessors.fillGradientStops.get = function () { return this._fillGradientStops; }; prototypeAccessors.fillGradientStops.set = function (fillGradientStops) // eslint-disable-line require-jsdoc { if (!areArraysEqual(this._fillGradientStops,fillGradientStops)) { this._fillGradientStops = fillGradientStops; this.styleID++; } }; /** * The font family * * @member {string|string[]} */ prototypeAccessors.fontFamily.get = function () { return this._fontFamily; }; prototypeAccessors.fontFamily.set = function (fontFamily) // eslint-disable-line require-jsdoc { if (this.fontFamily !== fontFamily) { this._fontFamily = fontFamily; this.styleID++; } }; /** * The font size * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') * * @member {number|string} */ prototypeAccessors.fontSize.get = function () { return this._fontSize; }; prototypeAccessors.fontSize.set = function (fontSize) // eslint-disable-line require-jsdoc { if (this._fontSize !== fontSize) { this._fontSize = fontSize; this.styleID++; } }; /** * The font style * ('normal', 'italic' or 'oblique') * * @member {string} */ prototypeAccessors.fontStyle.get = function () { return this._fontStyle; }; prototypeAccessors.fontStyle.set = function (fontStyle) // eslint-disable-line require-jsdoc { if (this._fontStyle !== fontStyle) { this._fontStyle = fontStyle; this.styleID++; } }; /** * The font variant * ('normal' or 'small-caps') * * @member {string} */ prototypeAccessors.fontVariant.get = function () { return this._fontVariant; }; prototypeAccessors.fontVariant.set = function (fontVariant) // eslint-disable-line require-jsdoc { if (this._fontVariant !== fontVariant) { this._fontVariant = fontVariant; this.styleID++; } }; /** * The font weight * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') * * @member {string} */ prototypeAccessors.fontWeight.get = function () { return this._fontWeight; }; prototypeAccessors.fontWeight.set = function (fontWeight) // eslint-disable-line require-jsdoc { if (this._fontWeight !== fontWeight) { this._fontWeight = fontWeight; this.styleID++; } }; /** * The amount of spacing between letters, default is 0 * * @member {number} */ prototypeAccessors.letterSpacing.get = function () { return this._letterSpacing; }; prototypeAccessors.letterSpacing.set = function (letterSpacing) // eslint-disable-line require-jsdoc { if (this._letterSpacing !== letterSpacing) { this._letterSpacing = letterSpacing; this.styleID++; } }; /** * The line height, a number that represents the vertical space that a letter uses * * @member {number} */ prototypeAccessors.lineHeight.get = function () { return this._lineHeight; }; prototypeAccessors.lineHeight.set = function (lineHeight) // eslint-disable-line require-jsdoc { if (this._lineHeight !== lineHeight) { this._lineHeight = lineHeight; this.styleID++; } }; /** * The space between lines * * @member {number} */ prototypeAccessors.leading.get = function () { return this._leading; }; prototypeAccessors.leading.set = function (leading) // eslint-disable-line require-jsdoc { if (this._leading !== leading) { this._leading = leading; this.styleID++; } }; /** * The lineJoin property sets the type of corner created, it can resolve spiked text issues. * Default is 'miter' (creates a sharp corner). * * @member {string} */ prototypeAccessors.lineJoin.get = function () { return this._lineJoin; }; prototypeAccessors.lineJoin.set = function (lineJoin) // eslint-disable-line require-jsdoc { if (this._lineJoin !== lineJoin) { this._lineJoin = lineJoin; this.styleID++; } }; /** * The miter limit to use when using the 'miter' lineJoin mode * This can reduce or increase the spikiness of rendered text. * * @member {number} */ prototypeAccessors.miterLimit.get = function () { return this._miterLimit; }; prototypeAccessors.miterLimit.set = function (miterLimit) // eslint-disable-line require-jsdoc { if (this._miterLimit !== miterLimit) { this._miterLimit = miterLimit; this.styleID++; } }; /** * Occasionally some fonts are cropped. Adding some padding will prevent this from happening * by adding padding to all sides of the text. * * @member {number} */ prototypeAccessors.padding.get = function () { return this._padding; }; prototypeAccessors.padding.set = function (padding) // eslint-disable-line require-jsdoc { if (this._padding !== padding) { this._padding = padding; this.styleID++; } }; /** * A canvas fillstyle that will be used on the text stroke * e.g 'blue', '#FCFF00' * * @member {string|number} */ prototypeAccessors.stroke.get = function () { return this._stroke; }; prototypeAccessors.stroke.set = function (stroke) // eslint-disable-line require-jsdoc { var outputColor = getColor(stroke); if (this._stroke !== outputColor) { this._stroke = outputColor; this.styleID++; } }; /** * A number that represents the thickness of the stroke. * Default is 0 (no stroke) * * @member {number} */ prototypeAccessors.strokeThickness.get = function () { return this._strokeThickness; }; prototypeAccessors.strokeThickness.set = function (strokeThickness) // eslint-disable-line require-jsdoc { if (this._strokeThickness !== strokeThickness) { this._strokeThickness = strokeThickness; this.styleID++; } }; /** * The baseline of the text that is rendered. * * @member {string} */ prototypeAccessors.textBaseline.get = function () { return this._textBaseline; }; prototypeAccessors.textBaseline.set = function (textBaseline) // eslint-disable-line require-jsdoc { if (this._textBaseline !== textBaseline) { this._textBaseline = textBaseline; this.styleID++; } }; /** * Trim transparent borders * * @member {boolean} */ prototypeAccessors.trim.get = function () { return this._trim; }; prototypeAccessors.trim.set = function (trim) // eslint-disable-line require-jsdoc { if (this._trim !== trim) { this._trim = trim; this.styleID++; } }; /** * How newlines and spaces should be handled. * Default is 'pre' (preserve, preserve). * * value | New lines | Spaces * --- | --- | --- * 'normal' | Collapse | Collapse * 'pre' | Preserve | Preserve * 'pre-line' | Preserve | Collapse * * @member {string} */ prototypeAccessors.whiteSpace.get = function () { return this._whiteSpace; }; prototypeAccessors.whiteSpace.set = function (whiteSpace) // eslint-disable-line require-jsdoc { if (this._whiteSpace !== whiteSpace) { this._whiteSpace = whiteSpace; this.styleID++; } }; /** * Indicates if word wrap should be used * * @member {boolean} */ prototypeAccessors.wordWrap.get = function () { return this._wordWrap; }; prototypeAccessors.wordWrap.set = function (wordWrap) // eslint-disable-line require-jsdoc { if (this._wordWrap !== wordWrap) { this._wordWrap = wordWrap; this.styleID++; } }; /** * The width at which text will wrap, it needs wordWrap to be set to true * * @member {number} */ prototypeAccessors.wordWrapWidth.get = function () { return this._wordWrapWidth; }; prototypeAccessors.wordWrapWidth.set = function (wordWrapWidth) // eslint-disable-line require-jsdoc { if (this._wordWrapWidth !== wordWrapWidth) { this._wordWrapWidth = wordWrapWidth; this.styleID++; } }; /** * Generates a font style string to use for `TextMetrics.measureFont()`. * * @return {string} Font style string, for passing to `TextMetrics.measureFont()` */ TextStyle.prototype.toFontString = function toFontString () { // build canvas api font setting from individual components. Convert a numeric this.fontSize to px var fontSizeString = (typeof this.fontSize === 'number') ? ((this.fontSize) + "px") : this.fontSize; // Clean-up fontFamily property by quoting each font name // this will support font names with spaces var fontFamilies = this.fontFamily; if (!Array.isArray(this.fontFamily)) { fontFamilies = this.fontFamily.split(','); } for (var i = fontFamilies.length - 1; i >= 0; i--) { // Trim any extra white-space var fontFamily = fontFamilies[i].trim(); // Check if font already contains strings if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) { fontFamily = "\"" + fontFamily + "\""; } fontFamilies[i] = fontFamily; } return ((this.fontStyle) + " " + (this.fontVariant) + " " + (this.fontWeight) + " " + fontSizeString + " " + (fontFamilies.join(','))); }; Object.defineProperties( TextStyle.prototype, prototypeAccessors ); /** * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. * @private * @param {number|number[]} color * @return {string} The color as a string. */ function getSingleColor(color) { if (typeof color === 'number') { return utils.hex2string(color); } else if ( typeof color === 'string' ) { if ( color.indexOf('0x') === 0 ) { color = color.replace('0x', '#'); } } return color; } /** * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. * This version can also convert array of colors * @private * @param {number|number[]} color * @return {string} The color as a string. */ function getColor(color) { if (!Array.isArray(color)) { return getSingleColor(color); } else { for (var i = 0; i < color.length; ++i) { color[i] = getSingleColor(color[i]); } return color; } } /** * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. * This version can also convert array of colors * @private * @param {Array} array1 First array to compare * @param {Array} array2 Second array to compare * @return {boolean} Do the arrays contain the same values in the same order */ function areArraysEqual(array1, array2) { if (!Array.isArray(array1) || !Array.isArray(array2)) { return false; } if (array1.length !== array2.length) { return false; } for (var i = 0; i < array1.length; ++i) { if (array1[i] !== array2[i]) { return false; } } return true; } /** * Utility function to ensure that object properties are copied by value, and not by reference * @private * @param {Object} target Target object to copy properties into * @param {Object} source Source object for the properties to copy * @param {string} propertyObj Object containing properties names we want to loop over */ function deepCopyProperties(target, source, propertyObj) { for (var prop in propertyObj) { if (Array.isArray(source[prop])) { target[prop] = source[prop].slice(); } else { target[prop] = source[prop]; } } } /** * The TextMetrics object represents the measurement of a block of text with a specified style. * * ```js * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) * ``` * * @class * @memberof PIXI */ var TextMetrics = function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { /** * The text that was measured * * @member {string} */ this.text = text; /** * The style that was measured * * @member {PIXI.TextStyle} */ this.style = style; /** * The measured width of the text * * @member {number} */ this.width = width; /** * The measured height of the text * * @member {number} */ this.height = height; /** * An array of lines of the text broken by new lines and wrapping is specified in style * * @member {string[]} */ this.lines = lines; /** * An array of the line widths for each line matched to `lines` * * @member {number[]} */ this.lineWidths = lineWidths; /** * The measured line height for this style * * @member {number} */ this.lineHeight = lineHeight; /** * The maximum line width for all measured lines * * @member {number} */ this.maxLineWidth = maxLineWidth; /** * The font properties object from TextMetrics.measureFont * * @member {PIXI.IFontMetrics} */ this.fontProperties = fontProperties; }; /** * Measures the supplied string of text and returns a Rectangle. * * @param {string} text - the text to measure. * @param {PIXI.TextStyle} style - the text style to use for measuring * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. * @return {PIXI.TextMetrics} measured width and height of the text. */ TextMetrics.measureText = function measureText (text, style, wordWrap, canvas) { if ( canvas === void 0 ) canvas = TextMetrics._canvas; wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap; var font = style.toFontString(); var fontProperties = TextMetrics.measureFont(font); // fallback in case UA disallow canvas data extraction // (toDataURI, getImageData functions) if (fontProperties.fontSize === 0) { fontProperties.fontSize = style.fontSize; fontProperties.ascent = style.fontSize; } var context = canvas.getContext('2d'); context.font = font; var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; var lines = outputText.split(/(?:\r\n|\r|\n)/); var lineWidths = new Array(lines.length); var maxLineWidth = 0; for (var i = 0; i < lines.length; i++) { var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing); lineWidths[i] = lineWidth; maxLineWidth = Math.max(maxLineWidth, lineWidth); } var width = maxLineWidth + style.strokeThickness; if (style.dropShadow) { width += style.dropShadowDistance; } var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + ((lines.length - 1) * (lineHeight + style.leading)); if (style.dropShadow) { height += style.dropShadowDistance; } return new TextMetrics( text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties ); }; /** * Applies newlines to a string to have it optimally fit into the horizontal * bounds set by the Text object's wordWrapWidth property. * * @private * @param {string} text - String to apply word wrapping to * @param {PIXI.TextStyle} style - the style to use when wrapping * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. * @return {string} New string with new lines applied where required */ TextMetrics.wordWrap = function wordWrap (text, style, canvas) { if ( canvas === void 0 ) canvas = TextMetrics._canvas; var context = canvas.getContext('2d'); var width = 0; var line = ''; var lines = ''; var cache = {}; var letterSpacing = style.letterSpacing; var whiteSpace = style.whiteSpace; // How to handle whitespaces var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); // whether or not spaces may be added to the beginning of lines var canPrependSpaces = !collapseSpaces; // There is letterSpacing after every char except the last one // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! // so for convenience the above needs to be compared to width + 1 extra letterSpace // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ // ________________________________________________ // And then the final space is simply no appended to each line var wordWrapWidth = style.wordWrapWidth + letterSpacing; // break text into words, spaces and newline chars var tokens = TextMetrics.tokenize(text); for (var i = 0; i < tokens.length; i++) { // get the word, space or newlineChar var token = tokens[i]; // if word is a new line if (TextMetrics.isNewline(token)) { // keep the new line if (!collapseNewlines) { lines += TextMetrics.addLine(line); canPrependSpaces = !collapseSpaces; line = ''; width = 0; continue; } // if we should collapse new lines // we simply convert it into a space token = ' '; } // if we should collapse repeated whitespaces if (collapseSpaces) { // check both this and the last tokens for spaces var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); if (currIsBreakingSpace && lastIsBreakingSpace) { continue; } } // get word width from cache if possible var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); // word is longer than desired bounds if (tokenWidth > wordWrapWidth) { // if we are not already at the beginning of a line if (line !== '') { // start newlines for overflow words lines += TextMetrics.addLine(line); line = ''; width = 0; } // break large word over multiple lines if (TextMetrics.canBreakWords(token, style.breakWords)) { // break word into characters var characters = TextMetrics.wordWrapSplit(token); // loop the characters for (var j = 0; j < characters.length; j++) { var char = characters[j]; var k = 1; // we are not at the end of the token while (characters[j + k]) { var nextChar = characters[j + k]; var lastChar = char[char.length - 1]; // should not split chars if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { // combine chars & move forward one char += nextChar; } else { break; } k++; } j += char.length - 1; var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); if (characterWidth + width > wordWrapWidth) { lines += TextMetrics.addLine(line); canPrependSpaces = false; line = ''; width = 0; } line += char; width += characterWidth; } } // run word out of the bounds else { // if there are words in this line already // finish that line and start a new one if (line.length > 0) { lines += TextMetrics.addLine(line); line = ''; width = 0; } var isLastToken = i === tokens.length - 1; // give it its own line if it's not the end lines += TextMetrics.addLine(token, !isLastToken); canPrependSpaces = false; line = ''; width = 0; } } // word could fit else { // word won't fit because of existing words // start a new line if (tokenWidth + width > wordWrapWidth) { // if its a space we don't want it canPrependSpaces = false; // add a new line lines += TextMetrics.addLine(line); // start a new line line = ''; width = 0; } // don't add spaces to the beginning of lines if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { // add the word to the current line line += token; // update width counter width += tokenWidth; } } } lines += TextMetrics.addLine(line, false); return lines; }; /** * Convienience function for logging each line added during the wordWrap * method * * @private * @param {string} line - The line of text to add * @param {boolean} newLine - Add new line character to end * @return {string} A formatted line */ TextMetrics.addLine = function addLine (line, newLine) { if ( newLine === void 0 ) newLine = true; line = TextMetrics.trimRight(line); line = (newLine) ? (line + "\n") : line; return line; }; /** * Gets & sets the widths of calculated characters in a cache object * * @private * @param {string} key The key * @param {number} letterSpacing The letter spacing * @param {object} cache The cache * @param {CanvasRenderingContext2D} context The canvas context * @return {number} The from cache. */ TextMetrics.getFromCache = function getFromCache (key, letterSpacing, cache, context) { var width = cache[key]; if (width === undefined) { var spacing = ((key.length) * letterSpacing); width = context.measureText(key).width + spacing; cache[key] = width; } return width; }; /** * Determines whether we should collapse breaking spaces * * @private * @param {string} whiteSpace The TextStyle property whiteSpace * @return {boolean} should collapse */ TextMetrics.collapseSpaces = function collapseSpaces (whiteSpace) { return (whiteSpace === 'normal' || whiteSpace === 'pre-line'); }; /** * Determines whether we should collapse newLine chars * * @private * @param {string} whiteSpace The white space * @return {boolean} should collapse */ TextMetrics.collapseNewlines = function collapseNewlines (whiteSpace) { return (whiteSpace === 'normal'); }; /** * trims breaking whitespaces from string * * @private * @param {string} text The text * @return {string} trimmed string */ TextMetrics.trimRight = function trimRight (text) { if (typeof text !== 'string') { return ''; } for (var i = text.length - 1; i >= 0; i--) { var char = text[i]; if (!TextMetrics.isBreakingSpace(char)) { break; } text = text.slice(0, -1); } return text; }; /** * Determines if char is a newline. * * @private * @param {string} char The character * @return {boolean} True if newline, False otherwise. */ TextMetrics.isNewline = function isNewline (char) { if (typeof char !== 'string') { return false; } return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0); }; /** * Determines if char is a breaking whitespace. * * @private * @param {string} char The character * @return {boolean} True if whitespace, False otherwise. */ TextMetrics.isBreakingSpace = function isBreakingSpace (char) { if (typeof char !== 'string') { return false; } return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0); }; /** * Splits a string into words, breaking-spaces and newLine characters * * @private * @param {string} text The text * @return {string[]} A tokenized array */ TextMetrics.tokenize = function tokenize (text) { var tokens = []; var token = ''; if (typeof text !== 'string') { return tokens; } for (var i = 0; i < text.length; i++) { var char = text[i]; if (TextMetrics.isBreakingSpace(char) || TextMetrics.isNewline(char)) { if (token !== '') { tokens.push(token); token = ''; } tokens.push(char); continue; } token += char; } if (token !== '') { tokens.push(token); } return tokens; }; /** * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. * * It allows one to customise which words should break * Examples are if the token is CJK or numbers. * It must return a boolean. * * @param {string} token The token * @param {boolean} breakWords The style attr break words * @return {boolean} whether to break word or not */ TextMetrics.canBreakWords = function canBreakWords (token, breakWords) { return breakWords; }; /** * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. * * It allows one to determine whether a pair of characters * should be broken by newlines * For example certain characters in CJK langs or numbers. * It must return a boolean. * * @param {string} char The character * @param {string} nextChar The next character * @param {string} token The token/word the characters are from * @param {number} index The index in the token of the char * @param {boolean} breakWords The style attr break words * @return {boolean} whether to break word or not */ TextMetrics.canBreakChars = function canBreakChars (char, nextChar, token, index, breakWords) // eslint-disable-line no-unused-vars { return true; }; /** * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. * * It is called when a token (usually a word) has to be split into separate pieces * in order to determine the point to break a word. * It must return an array of characters. * * @example * // Correctly splits emojis, eg "🤪🤪" will result in two element array, each with one emoji. * TextMetrics.wordWrapSplit = (token) => [...token]; * * @param {string} token The token to split * @return {string[]} The characters of the token */ TextMetrics.wordWrapSplit = function wordWrapSplit (token) { return token.split(''); }; /** * Calculates the ascent, descent and fontSize of a given font-style * * @static * @param {string} font - String representing the style of the font * @return {PIXI.IFontMetrics} Font properties object */ TextMetrics.measureFont = function measureFont (font) { // as this method is used for preparing assets, don't recalculate things if we don't need to if (TextMetrics._fonts[font]) { return TextMetrics._fonts[font]; } var properties = {}; var canvas = TextMetrics._canvas; var context = TextMetrics._context; context.font = font; var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; var width = Math.ceil(context.measureText(metricsString).width); var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); var height = 2 * baseline; baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; canvas.width = width; canvas.height = height; context.fillStyle = '#f00'; context.fillRect(0, 0, width, height); context.font = font; context.textBaseline = 'alphabetic'; context.fillStyle = '#000'; context.fillText(metricsString, 0, baseline); var imagedata = context.getImageData(0, 0, width, height).data; var pixels = imagedata.length; var line = width * 4; var i = 0; var idx = 0; var stop = false; // ascent. scan from top to bottom until we find a non red pixel for (i = 0; i < baseline; ++i) { for (var j = 0; j < line; j += 4) { if (imagedata[idx + j] !== 255) { stop = true; break; } } if (!stop) { idx += line; } else { break; } } properties.ascent = baseline - i; idx = pixels - line; stop = false; // descent. scan from bottom to top until we find a non red pixel for (i = height; i > baseline; --i) { for (var j$1 = 0; j$1 < line; j$1 += 4) { if (imagedata[idx + j$1] !== 255) { stop = true; break; } } if (!stop) { idx -= line; } else { break; } } properties.descent = i - baseline; properties.fontSize = properties.ascent + properties.descent; TextMetrics._fonts[font] = properties; return properties; }; /** * Clear font metrics in metrics cache. * * @static * @param {string} [font] - font name. If font name not set then clear cache for all fonts. */ TextMetrics.clearMetrics = function clearMetrics (font) { if ( font === void 0 ) font = ''; if (font) { delete TextMetrics._fonts[font]; } else { TextMetrics._fonts = {}; } }; /** * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. * * @typedef {object} FontMetrics * @property {number} ascent - The ascent distance * @property {number} descent - The descent distance * @property {number} fontSize - Font size from ascent to descent * @memberof PIXI.TextMetrics * @private */ var canvas = (function () { try { // OffscreenCanvas2D measureText can be up to 40% faster. var c = new OffscreenCanvas(0, 0); var context = c.getContext('2d'); if (context && context.measureText) { return c; } return document.createElement('canvas'); } catch (ex) { return document.createElement('canvas'); } })(); canvas.width = canvas.height = 10; /** * Cached canvas element for measuring text * * @memberof PIXI.TextMetrics * @type {HTMLCanvasElement} * @private */ TextMetrics._canvas = canvas; /** * Cache for context to use. * * @memberof PIXI.TextMetrics * @type {CanvasRenderingContext2D} * @private */ TextMetrics._context = canvas.getContext('2d'); /** * Cache of {@see PIXI.TextMetrics.FontMetrics} objects. * * @memberof PIXI.TextMetrics * @type {Object} * @private */ TextMetrics._fonts = {}; /** * String used for calculate font metrics. * These characters are all tall to help calculate the height required for text. * * @static * @memberof PIXI.TextMetrics * @name METRICS_STRING * @type {string} * @default |ÉqÅ */ TextMetrics.METRICS_STRING = '|ÉqÅ'; /** * Baseline symbol for calculate font metrics. * * @static * @memberof PIXI.TextMetrics * @name BASELINE_SYMBOL * @type {string} * @default M */ TextMetrics.BASELINE_SYMBOL = 'M'; /** * Baseline multiplier for calculate font metrics. * * @static * @memberof PIXI.TextMetrics * @name BASELINE_MULTIPLIER * @type {number} * @default 1.4 */ TextMetrics.BASELINE_MULTIPLIER = 1.4; /** * Cache of new line chars. * * @memberof PIXI.TextMetrics * @type {number[]} * @private */ TextMetrics._newlines = [ 0x000A, // line feed 0x000D ]; /** * Cache of breaking spaces. * * @memberof PIXI.TextMetrics * @type {number[]} * @private */ TextMetrics._breakingSpaces = [ 0x0009, // character tabulation 0x0020, // space 0x2000, // en quad 0x2001, // em quad 0x2002, // en space 0x2003, // em space 0x2004, // three-per-em space 0x2005, // four-per-em space 0x2006, // six-per-em space 0x2008, // punctuation space 0x2009, // thin space 0x200A, // hair space 0x205F, // medium mathematical space 0x3000 ]; /** * A number, or a string containing a number. * * @memberof PIXI * @typedef IFontMetrics * @property {number} ascent - Font ascent * @property {number} descent - Font descent * @property {number} fontSize - Font size */ /* eslint max-depth: [2, 8] */ var defaultDestroyOptions = { texture: true, children: false, baseTexture: true, }; /** * A Text Object will create a line or multiple lines of text. * * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). * * The primary advantage of this class over BitmapText is that you have great control over the style of the next, * which you can change at runtime. * * The primary disadvantages is that each piece of text has it's own texture, which can use more memory. * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time. * * To split a line you can use '\n' in your text string, or, on the `style` object, * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value. * * A Text can be created directly from a string and a style object, * which can be generated [here](https://pixijs.io/pixi-text-style). * * ```js * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); * ``` * * @class * @extends PIXI.Sprite * @memberof PIXI */ var Text = /*@__PURE__*/(function (Sprite) { function Text(text, style, canvas) { canvas = canvas || document.createElement('canvas'); canvas.width = 3; canvas.height = 3; var texture = core.Texture.from(canvas); texture.orig = new math.Rectangle(); texture.trim = new math.Rectangle(); Sprite.call(this, texture); /** * The canvas element that everything is drawn to * * @member {HTMLCanvasElement} */ this.canvas = canvas; /** * The canvas 2d context that everything is drawn with * @member {CanvasRenderingContext2D} */ this.context = this.canvas.getContext('2d'); /** * The resolution / device pixel ratio of the canvas. * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. * @member {number} * @default 1 */ this._resolution = settings.settings.RESOLUTION; this._autoResolution = true; /** * Private tracker for the current text. * * @member {string} * @private */ this._text = null; /** * Private tracker for the current style. * * @member {object} * @private */ this._style = null; /** * Private listener to track style changes. * * @member {Function} * @private */ this._styleListener = null; /** * Private tracker for the current font. * * @member {string} * @private */ this._font = ''; this.text = text; this.style = style; this.localStyleID = -1; } if ( Sprite ) Text.__proto__ = Sprite; Text.prototype = Object.create( Sprite && Sprite.prototype ); Text.prototype.constructor = Text; var prototypeAccessors = { width: { configurable: true },height: { configurable: true },style: { configurable: true },text: { configurable: true },resolution: { configurable: true } }; /** * Renders text and updates it when needed. * * @private * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. */ Text.prototype.updateText = function updateText (respectDirty) { var style = this._style; // check if style has changed.. if (this.localStyleID !== style.styleID) { this.dirty = true; this.localStyleID = style.styleID; } if (!this.dirty && respectDirty) { return; } this._font = this._style.toFontString(); var context = this.context; var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas); var width = measured.width; var height = measured.height; var lines = measured.lines; var lineHeight = measured.lineHeight; var lineWidths = measured.lineWidths; var maxLineWidth = measured.maxLineWidth; var fontProperties = measured.fontProperties; this.canvas.width = Math.ceil((Math.max(1, width) + (style.padding * 2)) * this._resolution); this.canvas.height = Math.ceil((Math.max(1, height) + (style.padding * 2)) * this._resolution); context.scale(this._resolution, this._resolution); context.clearRect(0, 0, this.canvas.width, this.canvas.height); context.font = this._font; context.lineWidth = style.strokeThickness; context.textBaseline = style.textBaseline; context.lineJoin = style.lineJoin; context.miterLimit = style.miterLimit; var linePositionX; var linePositionY; // require 2 passes if a shadow; the first to draw the drop shadow, the second to draw the text var passesCount = style.dropShadow ? 2 : 1; // For v4, we drew text at the colours of the drop shadow underneath the normal text. This gave the correct zIndex, // but features such as alpha and shadowblur did not look right at all, since we were using actual text as a shadow. // // For v5.0.0, we moved over to just use the canvas API for drop shadows, which made them look much nicer and more // visually please, but now because the stroke is drawn and then the fill, drop shadows would appear on both the fill // and the stroke; and fill drop shadows would appear over the top of the stroke. // // For v5.1.1, the new route is to revert to v4 style of drawing text first to get the drop shadows underneath normal // text, but instead drawing text in the correct location, we'll draw it off screen (-paddingY), and then adjust the // drop shadow so only that appears on screen (+paddingY). Now we'll have the correct draw order of the shadow // beneath the text, whilst also having the proper text shadow styling. for (var i = 0; i < passesCount; ++i) { var isShadowPass = style.dropShadow && i === 0; var dsOffsetText = isShadowPass ? height * 2 : 0; // we only want the drop shadow, so put text way off-screen var dsOffsetShadow = dsOffsetText * this.resolution; if (isShadowPass) { // On Safari, text with gradient and drop shadows together do not position correctly // if the scale of the canvas is not 1: https://bugs.webkit.org/show_bug.cgi?id=197689 // Therefore we'll set the styles to be a plain black whilst generating this drop shadow context.fillStyle = 'black'; context.strokeStyle = 'black'; var dropShadowColor = style.dropShadowColor; var rgb = utils.hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : utils.string2hex(dropShadowColor)); context.shadowColor = "rgba(" + (rgb[0] * 255) + "," + (rgb[1] * 255) + "," + (rgb[2] * 255) + "," + (style.dropShadowAlpha) + ")"; context.shadowBlur = style.dropShadowBlur; context.shadowOffsetX = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * style.dropShadowDistance) + dsOffsetShadow; } else { // set canvas text styles context.fillStyle = this._generateFillStyle(style, lines); context.strokeStyle = style.stroke; context.shadowColor = 0; context.shadowBlur = 0; context.shadowOffsetX = 0; context.shadowOffsetY = 0; } // draw lines line by line for (var i$1 = 0; i$1 < lines.length; i$1++) { linePositionX = style.strokeThickness / 2; linePositionY = ((style.strokeThickness / 2) + (i$1 * lineHeight)) + fontProperties.ascent; if (style.align === 'right') { linePositionX += maxLineWidth - lineWidths[i$1]; } else if (style.align === 'center') { linePositionX += (maxLineWidth - lineWidths[i$1]) / 2; } if (style.stroke && style.strokeThickness) { this.drawLetterSpacing( lines[i$1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true ); } if (style.fill) { this.drawLetterSpacing( lines[i$1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText ); } } } this.updateTexture(); }; /** * Render the text with letter-spacing. * @param {string} text - The text to draw * @param {number} x - Horizontal position to draw the text * @param {number} y - Vertical position to draw the text * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the * text? If not, it's for the inside fill * @private */ Text.prototype.drawLetterSpacing = function drawLetterSpacing (text, x, y, isStroke) { if ( isStroke === void 0 ) isStroke = false; var style = this._style; // letterSpacing of 0 means normal var letterSpacing = style.letterSpacing; if (letterSpacing === 0) { if (isStroke) { this.context.strokeText(text, x, y); } else { this.context.fillText(text, x, y); } return; } var currentPosition = x; // Using Array.from correctly splits characters whilst keeping emoji together. // This is not supported on IE as it requires ES6, so regular text splitting occurs. // This also doesn't account for emoji that are multiple emoji put together to make something else. // Handling all of this would require a big library itself. // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516 // https://github.com/orling/grapheme-splitter var stringArray = Array.from ? Array.from(text) : text.split(''); var previousWidth = this.context.measureText(text).width; var currentWidth = 0; for (var i = 0; i < stringArray.length; ++i) { var currentChar = stringArray[i]; if (isStroke) { this.context.strokeText(currentChar, currentPosition, y); } else { this.context.fillText(currentChar, currentPosition, y); } currentWidth = this.context.measureText(text.substring(i + 1)).width; currentPosition += previousWidth - currentWidth + letterSpacing; previousWidth = currentWidth; } }; /** * Updates texture size based on canvas size * * @private */ Text.prototype.updateTexture = function updateTexture () { var canvas = this.canvas; if (this._style.trim) { var trimmed = utils.trimCanvas(canvas); if (trimmed.data) { canvas.width = trimmed.width; canvas.height = trimmed.height; this.context.putImageData(trimmed.data, 0, 0); } } var texture = this._texture; var style = this._style; var padding = style.trim ? 0 : style.padding; var baseTexture = texture.baseTexture; texture.trim.width = texture._frame.width = Math.ceil(canvas.width / this._resolution); texture.trim.height = texture._frame.height = Math.ceil(canvas.height / this._resolution); texture.trim.x = -padding; texture.trim.y = -padding; texture.orig.width = texture._frame.width - (padding * 2); texture.orig.height = texture._frame.height - (padding * 2); // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); baseTexture.setRealSize(canvas.width, canvas.height, this._resolution); this.dirty = false; }; /** * Renders the object using the WebGL renderer * * @private * @param {PIXI.Renderer} renderer - The renderer */ Text.prototype._render = function _render (renderer) { if (this._autoResolution && this._resolution !== renderer.resolution) { this._resolution = renderer.resolution; this.dirty = true; } this.updateText(true); Sprite.prototype._render.call(this, renderer); }; /** * Gets the local bounds of the text object. * * @param {PIXI.Rectangle} rect - The output rectangle. * @return {PIXI.Rectangle} The bounds. */ Text.prototype.getLocalBounds = function getLocalBounds (rect) { this.updateText(true); return Sprite.prototype.getLocalBounds.call(this, rect); }; /** * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. * @protected */ Text.prototype._calculateBounds = function _calculateBounds () { this.updateText(true); this.calculateVertices(); // if we have already done this on THIS frame. this._bounds.addQuad(this.vertexData); }; /** * Method to be called upon a TextStyle change. * @private */ Text.prototype._onStyleChange = function _onStyleChange () { this.dirty = true; }; /** * Generates the fill style. Can automatically generate a gradient based on the fill style being an array * * @private * @param {object} style - The style. * @param {string[]} lines - The lines of text. * @return {string|number|CanvasGradient} The fill style */ Text.prototype._generateFillStyle = function _generateFillStyle (style, lines) { if (!Array.isArray(style.fill)) { return style.fill; } else if (style.fill.length === 1) { return style.fill[0]; } // the gradient will be evenly spaced out according to how large the array is. // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 var gradient; var totalIterations; var currentIteration; var stop; // a dropshadow will enlarge the canvas and result in the gradient being // generated with the incorrect dimensions var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; var width = Math.ceil(this.canvas.width / this._resolution) - dropShadowCorrection; var height = Math.ceil(this.canvas.height / this._resolution) - dropShadowCorrection; // make a copy of the style settings, so we can manipulate them later var fill = style.fill.slice(); var fillGradientStops = style.fillGradientStops.slice(); // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 if (!fillGradientStops.length) { var lengthPlus1 = fill.length + 1; for (var i = 1; i < lengthPlus1; ++i) { fillGradientStops.push(i / lengthPlus1); } } // stop the bleeding of the last gradient on the line above to the top gradient of the this line // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 fill.unshift(style.fill[0]); fillGradientStops.unshift(0); fill.push(style.fill[style.fill.length - 1]); fillGradientStops.push(1); if (style.fillGradientType === TEXT_GRADIENT.LINEAR_VERTICAL) { // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 totalIterations = (fill.length + 1) * lines.length; currentIteration = 0; for (var i$1 = 0; i$1 < lines.length; i$1++) { currentIteration += 1; for (var j = 0; j < fill.length; j++) { if (typeof fillGradientStops[j] === 'number') { stop = (fillGradientStops[j] / lines.length) + (i$1 / lines.length); } else { stop = currentIteration / totalIterations; } gradient.addColorStop(stop, fill[j]); currentIteration++; } } } else { // start the gradient at the center left of the canvas, and end at the center right of the canvas gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); // can just evenly space out the gradients in this case, as multiple lines makes no difference // to an even left to right gradient totalIterations = fill.length + 1; currentIteration = 1; for (var i$2 = 0; i$2 < fill.length; i$2++) { if (typeof fillGradientStops[i$2] === 'number') { stop = fillGradientStops[i$2]; } else { stop = currentIteration / totalIterations; } gradient.addColorStop(stop, fill[i$2]); currentIteration++; } } return gradient; }; /** * Destroys this text object. * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as * the majority of the time the texture will not be shared with any other Sprites. * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options * have been set to that value * @param {boolean} [options.children=false] - if set to true, all the children will have their * destroy method called as well. 'options' will be passed on to those calls. * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well */ Text.prototype.destroy = function destroy (options) { if (typeof options === 'boolean') { options = { children: options }; } options = Object.assign({}, defaultDestroyOptions, options); Sprite.prototype.destroy.call(this, options); // make sure to reset the the context and canvas.. dont want this hanging around in memory! this.context = null; this.canvas = null; this._style = null; }; /** * The width of the Text, setting this will actually modify the scale to achieve the value set * * @member {number} */ prototypeAccessors.width.get = function () { this.updateText(true); return Math.abs(this.scale.x) * this._texture.orig.width; }; prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc { this.updateText(true); var s = utils.sign(this.scale.x) || 1; this.scale.x = s * value / this._texture.orig.width; this._width = value; }; /** * The height of the Text, setting this will actually modify the scale to achieve the value set * * @member {number} */ prototypeAccessors.height.get = function () { this.updateText(true); return Math.abs(this.scale.y) * this._texture.orig.height; }; prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc { this.updateText(true); var s = utils.sign(this.scale.y) || 1; this.scale.y = s * value / this._texture.orig.height; this._height = value; }; /** * Set the style of the text. Set up an event listener to listen for changes on the style * object and mark the text as dirty. * * @member {object|PIXI.TextStyle} */ prototypeAccessors.style.get = function () { return this._style; }; prototypeAccessors.style.set = function (style) // eslint-disable-line require-jsdoc { style = style || {}; if (style instanceof TextStyle) { this._style = style; } else { this._style = new TextStyle(style); } this.localStyleID = -1; this.dirty = true; }; /** * Set the copy for the text object. To split a line you can use '\n'. * * @member {string} */ prototypeAccessors.text.get = function () { return this._text; }; prototypeAccessors.text.set = function (text) // eslint-disable-line require-jsdoc { text = String(text === null || text === undefined ? '' : text); if (this._text === text) { return; } this._text = text; this.dirty = true; }; /** * The resolution / device pixel ratio of the canvas. * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. * @member {number} * @default 1 */ prototypeAccessors.resolution.get = function () { return this._resolution; }; prototypeAccessors.resolution.set = function (value) // eslint-disable-line require-jsdoc { this._autoResolution = false; if (this._resolution === value) { return; } this._resolution = value; this.dirty = true; }; Object.defineProperties( Text.prototype, prototypeAccessors ); return Text; }(sprite.Sprite)); exports.TEXT_GRADIENT = TEXT_GRADIENT; exports.Text = Text; exports.TextMetrics = TextMetrics; exports.TextStyle = TextStyle; },{"@pixi/core":7,"@pixi/math":21,"@pixi/settings":31,"@pixi/sprite":34,"@pixi/utils":39}],38:[function(require,module,exports){ /*! * @pixi/ticker - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/ticker is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var settings = require('@pixi/settings'); /** * Target frames per millisecond. * * @static * @name TARGET_FPMS * @memberof PIXI.settings * @type {number} * @default 0.06 */ settings.settings.TARGET_FPMS = 0.06; /** * Represents the update priorities used by internal PIXI classes when registered with * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower * priority items, such as render, should go later. * * @static * @constant * @name UPDATE_PRIORITY * @memberof PIXI * @enum {number} * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager} * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite} * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.Ticker#add}. * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility. */ (function (UPDATE_PRIORITY) { UPDATE_PRIORITY[UPDATE_PRIORITY["INTERACTION"] = 50] = "INTERACTION"; UPDATE_PRIORITY[UPDATE_PRIORITY["HIGH"] = 25] = "HIGH"; UPDATE_PRIORITY[UPDATE_PRIORITY["NORMAL"] = 0] = "NORMAL"; UPDATE_PRIORITY[UPDATE_PRIORITY["LOW"] = -25] = "LOW"; UPDATE_PRIORITY[UPDATE_PRIORITY["UTILITY"] = -50] = "UTILITY"; })(exports.UPDATE_PRIORITY || (exports.UPDATE_PRIORITY = {})); /** * Internal class for handling the priority sorting of ticker handlers. * * @private * @class * @memberof PIXI */ var TickerListener = /** @class */ (function () { /** * Constructor * @private * @param {Function} fn - The listener function to be added for one update * @param {*} [context=null] - The listener context * @param {number} [priority=0] - The priority for emitting * @param {boolean} [once=false] - If the handler should fire once */ function TickerListener(fn, context, priority, once) { if (context === void 0) { context = null; } if (priority === void 0) { priority = 0; } if (once === void 0) { once = false; } /** * The handler function to execute. * @private * @member {Function} */ this.fn = fn; /** * The calling to execute. * @private * @member {*} */ this.context = context; /** * The current priority. * @private * @member {number} */ this.priority = priority; /** * If this should only execute once. * @private * @member {boolean} */ this.once = once; /** * The next item in chain. * @private * @member {TickerListener} */ this.next = null; /** * The previous item in chain. * @private * @member {TickerListener} */ this.previous = null; /** * `true` if this listener has been destroyed already. * @member {boolean} * @private */ this._destroyed = false; } /** * Simple compare function to figure out if a function and context match. * @private * @param {Function} fn - The listener function to be added for one update * @param {any} [context] - The listener context * @return {boolean} `true` if the listener match the arguments */ TickerListener.prototype.match = function (fn, context) { if (context === void 0) { context = null; } return this.fn === fn && this.context === context; }; /** * Emit by calling the current function. * @private * @param {number} deltaTime - time since the last emit. * @return {TickerListener} Next ticker */ TickerListener.prototype.emit = function (deltaTime) { if (this.fn) { if (this.context) { this.fn.call(this.context, deltaTime); } else { this.fn(deltaTime); } } var redirect = this.next; if (this.once) { this.destroy(true); } // Soft-destroying should remove // the next reference if (this._destroyed) { this.next = null; } return redirect; }; /** * Connect to the list. * @private * @param {TickerListener} previous - Input node, previous listener */ TickerListener.prototype.connect = function (previous) { this.previous = previous; if (previous.next) { previous.next.previous = this; } this.next = previous.next; previous.next = this; }; /** * Destroy and don't use after this. * @private * @param {boolean} [hard = false] `true` to remove the `next` reference, this * is considered a hard destroy. Soft destroy maintains the next reference. * @return {TickerListener} The listener to redirect while emitting or removing. */ TickerListener.prototype.destroy = function (hard) { if (hard === void 0) { hard = false; } this._destroyed = true; this.fn = null; this.context = null; // Disconnect, hook up next and previous if (this.previous) { this.previous.next = this.next; } if (this.next) { this.next.previous = this.previous; } // Redirect to the next item var redirect = this.next; // Remove references this.next = hard ? null : redirect; this.previous = null; return redirect; }; return TickerListener; }()); /** * A Ticker class that runs an update loop that other objects listen to. * * This class is composed around listeners meant for execution on the next requested animation frame. * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners. * * @class * @memberof PIXI */ var Ticker = /** @class */ (function () { function Ticker() { var _this = this; /** * The first listener. All new listeners added are chained on this. * @private * @type {TickerListener} */ this._head = new TickerListener(null, null, Infinity); /** * Internal current frame request ID * @type {?number} * @private */ this._requestId = null; /** * Internal value managed by minFPS property setter and getter. * This is the maximum allowed milliseconds between updates. * @type {number} * @private */ this._maxElapsedMS = 100; /** * Internal value managed by maxFPS property setter and getter. * This is the minimum allowed milliseconds between updates. * @type {number} * @private */ this._minElapsedMS = 0; /** * Whether or not this ticker should invoke the method * {@link PIXI.Ticker#start} automatically * when a listener is added. * * @member {boolean} * @default false */ this.autoStart = false; /** * Scalar time value from last frame to this frame. * This value is capped by setting {@link PIXI.Ticker#minFPS} * and is scaled with {@link PIXI.Ticker#speed}. * **Note:** The cap may be exceeded by scaling. * * @member {number} * @default 1 */ this.deltaTime = 1; /** * Scaler time elapsed in milliseconds from last frame to this frame. * This value is capped by setting {@link PIXI.Ticker#minFPS} * and is scaled with {@link PIXI.Ticker#speed}. * **Note:** The cap may be exceeded by scaling. * If the platform supports DOMHighResTimeStamp, * this value will have a precision of 1 µs. * Defaults to target frame time * * @member {number} * @default 16.66 */ this.deltaMS = 1 / settings.settings.TARGET_FPMS; /** * Time elapsed in milliseconds from last frame to this frame. * Opposed to what the scalar {@link PIXI.Ticker#deltaTime} * is based, this value is neither capped nor scaled. * If the platform supports DOMHighResTimeStamp, * this value will have a precision of 1 µs. * Defaults to target frame time * * @member {number} * @default 16.66 */ this.elapsedMS = 1 / settings.settings.TARGET_FPMS; /** * The last time {@link PIXI.Ticker#update} was invoked. * This value is also reset internally outside of invoking * update, but only when a new animation frame is requested. * If the platform supports DOMHighResTimeStamp, * this value will have a precision of 1 µs. * * @member {number} * @default -1 */ this.lastTime = -1; /** * Factor of current {@link PIXI.Ticker#deltaTime}. * @example * // Scales ticker.deltaTime to what would be * // the equivalent of approximately 120 FPS * ticker.speed = 2; * * @member {number} * @default 1 */ this.speed = 1; /** * Whether or not this ticker has been started. * `true` if {@link PIXI.Ticker#start} has been called. * `false` if {@link PIXI.Ticker#stop} has been called. * While `false`, this value may change to `true` in the * event of {@link PIXI.Ticker#autoStart} being `true` * and a listener is added. * * @member {boolean} * @default false */ this.started = false; /** * If enabled, deleting is disabled. * @member {boolean} * @default false * @private */ this._protected = false; /** * The last time keyframe was executed. * Maintains a relatively fixed interval with the previous value. * @member {number} * @default -1 * @private */ this._lastFrame = -1; /** * Internal tick method bound to ticker instance. * This is because in early 2015, Function.bind * is still 60% slower in high performance scenarios. * Also separating frame requests from update method * so listeners may be called at any time and with * any animation API, just invoke ticker.update(time). * * @private * @param {number} time - Time since last tick. */ this._tick = function (time) { _this._requestId = null; if (_this.started) { // Invoke listeners now _this.update(time); // Listener side effects may have modified ticker state. if (_this.started && _this._requestId === null && _this._head.next) { _this._requestId = requestAnimationFrame(_this._tick); } } }; } /** * Conditionally requests a new animation frame. * If a frame has not already been requested, and if the internal * emitter has listeners, a new frame is requested. * * @private */ Ticker.prototype._requestIfNeeded = function () { if (this._requestId === null && this._head.next) { // ensure callbacks get correct delta this.lastTime = performance.now(); this._lastFrame = this.lastTime; this._requestId = requestAnimationFrame(this._tick); } }; /** * Conditionally cancels a pending animation frame. * * @private */ Ticker.prototype._cancelIfNeeded = function () { if (this._requestId !== null) { cancelAnimationFrame(this._requestId); this._requestId = null; } }; /** * Conditionally requests a new animation frame. * If the ticker has been started it checks if a frame has not already * been requested, and if the internal emitter has listeners. If these * conditions are met, a new frame is requested. If the ticker has not * been started, but autoStart is `true`, then the ticker starts now, * and continues with the previous conditions to request a new frame. * * @private */ Ticker.prototype._startIfPossible = function () { if (this.started) { this._requestIfNeeded(); } else if (this.autoStart) { this.start(); } }; /** * Register a handler for tick events. Calls continuously unless * it is removed or the ticker is stopped. * * @param {Function} fn - The listener function to be added for updates * @param {*} [context] - The listener context * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting * @returns {PIXI.Ticker} This instance of a ticker */ Ticker.prototype.add = function (fn, context, priority) { if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } return this._addListener(new TickerListener(fn, context, priority)); }; /** * Add a handler for the tick event which is only execute once. * * @param {Function} fn - The listener function to be added for one update * @param {*} [context] - The listener context * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting * @returns {PIXI.Ticker} This instance of a ticker */ Ticker.prototype.addOnce = function (fn, context, priority) { if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } return this._addListener(new TickerListener(fn, context, priority, true)); }; /** * Internally adds the event handler so that it can be sorted by priority. * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run * before the rendering. * * @private * @param {TickerListener} listener - Current listener being added. * @returns {PIXI.Ticker} This instance of a ticker */ Ticker.prototype._addListener = function (listener) { // For attaching to head var current = this._head.next; var previous = this._head; // Add the first item if (!current) { listener.connect(previous); } else { // Go from highest to lowest priority while (current) { if (listener.priority > current.priority) { listener.connect(previous); break; } previous = current; current = current.next; } // Not yet connected if (!listener.previous) { listener.connect(previous); } } this._startIfPossible(); return this; }; /** * Removes any handlers matching the function and context parameters. * If no handlers are left after removing, then it cancels the animation frame. * * @param {Function} fn - The listener function to be removed * @param {*} [context] - The listener context to be removed * @returns {PIXI.Ticker} This instance of a ticker */ Ticker.prototype.remove = function (fn, context) { var listener = this._head.next; while (listener) { // We found a match, lets remove it // no break to delete all possible matches // incase a listener was added 2+ times if (listener.match(fn, context)) { listener = listener.destroy(); } else { listener = listener.next; } } if (!this._head.next) { this._cancelIfNeeded(); } return this; }; Object.defineProperty(Ticker.prototype, "count", { /** * Counts the number of listeners on this ticker. * * @returns {number} The number of listeners on this ticker */ get: function () { if (!this._head) { return 0; } var count = 0; var current = this._head; while ((current = current.next)) { count++; } return count; }, enumerable: true, configurable: true }); /** * Starts the ticker. If the ticker has listeners * a new animation frame is requested at this point. */ Ticker.prototype.start = function () { if (!this.started) { this.started = true; this._requestIfNeeded(); } }; /** * Stops the ticker. If the ticker has requested * an animation frame it is canceled at this point. */ Ticker.prototype.stop = function () { if (this.started) { this.started = false; this._cancelIfNeeded(); } }; /** * Destroy the ticker and don't use after this. Calling * this method removes all references to internal events. */ Ticker.prototype.destroy = function () { if (!this._protected) { this.stop(); var listener = this._head.next; while (listener) { listener = listener.destroy(true); } this._head.destroy(); this._head = null; } }; /** * Triggers an update. An update entails setting the * current {@link PIXI.Ticker#elapsedMS}, * the current {@link PIXI.Ticker#deltaTime}, * invoking all listeners with current deltaTime, * and then finally setting {@link PIXI.Ticker#lastTime} * with the value of currentTime that was provided. * This method will be called automatically by animation * frame callbacks if the ticker instance has been started * and listeners are added. * * @param {number} [currentTime=performance.now()] - the current time of execution */ Ticker.prototype.update = function (currentTime) { if (currentTime === void 0) { currentTime = performance.now(); } var elapsedMS; // If the difference in time is zero or negative, we ignore most of the work done here. // If there is no valid difference, then should be no reason to let anyone know about it. // A zero delta, is exactly that, nothing should update. // // The difference in time can be negative, and no this does not mean time traveling. // This can be the result of a race condition between when an animation frame is requested // on the current JavaScript engine event loop, and when the ticker's start method is invoked // (which invokes the internal _requestIfNeeded method). If a frame is requested before // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, // can receive a time argument that can be less than the lastTime value that was set within // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. // // This check covers this browser engine timing issue, as well as if consumers pass an invalid // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. if (currentTime > this.lastTime) { // Save uncapped elapsedMS for measurement elapsedMS = this.elapsedMS = currentTime - this.lastTime; // cap the milliseconds elapsed used for deltaTime if (elapsedMS > this._maxElapsedMS) { elapsedMS = this._maxElapsedMS; } elapsedMS *= this.speed; // If not enough time has passed, exit the function. // Get ready for next frame by setting _lastFrame, but based on _minElapsedMS // adjustment to ensure a relatively stable interval. if (this._minElapsedMS) { var delta = currentTime - this._lastFrame | 0; if (delta < this._minElapsedMS) { return; } this._lastFrame = currentTime - (delta % this._minElapsedMS); } this.deltaMS = elapsedMS; this.deltaTime = this.deltaMS * settings.settings.TARGET_FPMS; // Cache a local reference, in-case ticker is destroyed // during the emit, we can still check for head.next var head = this._head; // Invoke listeners added to internal emitter var listener = head.next; while (listener) { listener = listener.emit(this.deltaTime); } if (!head.next) { this._cancelIfNeeded(); } } else { this.deltaTime = this.deltaMS = this.elapsedMS = 0; } this.lastTime = currentTime; }; Object.defineProperty(Ticker.prototype, "FPS", { /** * The frames per second at which this ticker is running. * The default is approximately 60 in most modern browsers. * **Note:** This does not factor in the value of * {@link PIXI.Ticker#speed}, which is specific * to scaling {@link PIXI.Ticker#deltaTime}. * * @member {number} * @readonly */ get: function () { return 1000 / this.elapsedMS; }, enumerable: true, configurable: true }); Object.defineProperty(Ticker.prototype, "minFPS", { /** * Manages the maximum amount of milliseconds allowed to * elapse between invoking {@link PIXI.Ticker#update}. * This value is used to cap {@link PIXI.Ticker#deltaTime}, * but does not effect the measured value of {@link PIXI.Ticker#FPS}. * When setting this property it is clamped to a value between * `0` and `PIXI.settings.TARGET_FPMS * 1000`. * * @member {number} * @default 10 */ get: function () { return 1000 / this._maxElapsedMS; }, set: function (fps) { // Minimum must be below the maxFPS var minFPS = Math.min(this.maxFPS, fps); // Must be at least 0, but below 1 / settings.TARGET_FPMS var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings.settings.TARGET_FPMS); this._maxElapsedMS = 1 / minFPMS; }, enumerable: true, configurable: true }); Object.defineProperty(Ticker.prototype, "maxFPS", { /** * Manages the minimum amount of milliseconds required to * elapse between invoking {@link PIXI.Ticker#update}. * This will effect the measured value of {@link PIXI.Ticker#FPS}. * If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can. * Otherwise it will be at least `minFPS` * * @member {number} * @default 0 */ get: function () { if (this._minElapsedMS) { return Math.round(1000 / this._minElapsedMS); } return 0; }, set: function (fps) { if (fps === 0) { this._minElapsedMS = 0; } else { // Max must be at least the minFPS var maxFPS = Math.max(this.minFPS, fps); this._minElapsedMS = 1 / (maxFPS / 1000); } }, enumerable: true, configurable: true }); Object.defineProperty(Ticker, "shared", { /** * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by * {@link PIXI.VideoResource} to update animation frames / video textures. * * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true. * * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker. * * @example * let ticker = PIXI.Ticker.shared; * // Set this to prevent starting this ticker when listeners are added. * // By default this is true only for the PIXI.Ticker.shared instance. * ticker.autoStart = false; * // FYI, call this to ensure the ticker is stopped. It should be stopped * // if you have not attempted to render anything yet. * ticker.stop(); * // Call this when you are ready for a running shared ticker. * ticker.start(); * * @example * // You may use the shared ticker to render... * let renderer = PIXI.autoDetectRenderer(); * let stage = new PIXI.Container(); * document.body.appendChild(renderer.view); * ticker.add(function (time) { * renderer.render(stage); * }); * * @example * // Or you can just update it manually. * ticker.autoStart = false; * ticker.stop(); * function animate(time) { * ticker.update(time); * renderer.render(stage); * requestAnimationFrame(animate); * } * animate(performance.now()); * * @member {PIXI.Ticker} * @static */ get: function () { if (!Ticker._shared) { var shared = Ticker._shared = new Ticker(); shared.autoStart = true; shared._protected = true; } return Ticker._shared; }, enumerable: true, configurable: true }); Object.defineProperty(Ticker, "system", { /** * The system ticker instance used by {@link PIXI.interaction.InteractionManager} and by * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused, * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused. * * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. * * @member {PIXI.Ticker} * @static */ get: function () { if (!Ticker._system) { var system = Ticker._system = new Ticker(); system.autoStart = true; system._protected = true; } return Ticker._system; }, enumerable: true, configurable: true }); return Ticker; }()); /** * Middleware for for Application Ticker. * * @example * import {TickerPlugin} from '@pixi/ticker'; * import {Application} from '@pixi/app'; * Application.registerPlugin(TickerPlugin); * * @class * @memberof PIXI */ var TickerPlugin = /** @class */ (function () { function TickerPlugin() { } /** * Initialize the plugin with scope of application instance * * @static * @private * @param {object} [options] - See application options */ TickerPlugin.init = function (options) { var _this = this; // Set default options = Object.assign({ autoStart: true, sharedTicker: false, }, options); // Create ticker setter Object.defineProperty(this, 'ticker', { set: function (ticker) { if (this._ticker) { this._ticker.remove(this.render, this); } this._ticker = ticker; if (ticker) { ticker.add(this.render, this, exports.UPDATE_PRIORITY.LOW); } }, get: function () { return this._ticker; }, }); /** * Convenience method for stopping the render. * * @method PIXI.Application#stop */ this.stop = function () { _this._ticker.stop(); }; /** * Convenience method for starting the render. * * @method PIXI.Application#start */ this.start = function () { _this._ticker.start(); }; /** * Internal reference to the ticker. * * @type {PIXI.Ticker} * @name _ticker * @memberof PIXI.Application# * @private */ this._ticker = null; /** * Ticker for doing render updates. * * @type {PIXI.Ticker} * @name ticker * @memberof PIXI.Application# * @default PIXI.Ticker.shared */ this.ticker = options.sharedTicker ? Ticker.shared : new Ticker(); // Start the rendering if (options.autoStart) { this.start(); } }; /** * Clean up the ticker, scoped to application. * * @static * @private */ TickerPlugin.destroy = function () { if (this._ticker) { var oldTicker = this._ticker; this.ticker = null; oldTicker.destroy(); } }; return TickerPlugin; }()); exports.Ticker = Ticker; exports.TickerPlugin = TickerPlugin; },{"@pixi/settings":31}],39:[function(require,module,exports){ /*! * @pixi/utils - v5.2.1 * Compiled Tue, 28 Jan 2020 23:33:11 UTC * * @pixi/utils is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var settings = require('@pixi/settings'); var eventemitter3 = _interopDefault(require('eventemitter3')); var earcut = _interopDefault(require('earcut')); var _url = require('url'); var _url__default = _interopDefault(_url); var constants = require('@pixi/constants'); /** * The prefix that denotes a URL is for a retina asset. * * @static * @name RETINA_PREFIX * @memberof PIXI.settings * @type {RegExp} * @default /@([0-9\.]+)x/ * @example `@2x` */ settings.settings.RETINA_PREFIX = /@([0-9\.]+)x/; /** * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function. * For most scenarios this should be left as true, as otherwise the user may have a poor experience. * However, it can be useful to disable under certain scenarios, such as headless unit tests. * * @static * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT * @memberof PIXI.settings * @type {boolean} * @default true */ settings.settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = true; var saidHello = false; var VERSION = '5.2.1'; /** * Skips the hello message of renderers that are created after this is run. * * @function skipHello * @memberof PIXI.utils */ function skipHello() { saidHello = true; } /** * Logs out the version and renderer information for this running instance of PIXI. * If you don't want to see this message you can run `PIXI.utils.skipHello()` before * creating your renderer. Keep in mind that doing that will forever make you a jerk face. * * @static * @function sayHello * @memberof PIXI.utils * @param {string} type - The string renderer type to log. */ function sayHello(type) { var _a; if (saidHello) { return; } if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { var args = [ "\n %c %c %c PixiJS " + VERSION + " - \u2730 " + type + " \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n", 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;' ]; (_a = window.console).log.apply(_a, args); } else if (window.console) { window.console.log("PixiJS " + VERSION + " - " + type + " - http://www.pixijs.com/"); } saidHello = true; } var supported; /** * Helper for checking for WebGL support. * * @memberof PIXI.utils * @function isWebGLSupported * @return {boolean} Is WebGL supported. */ function isWebGLSupported() { if (typeof supported === 'undefined') { supported = (function supported() { var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: settings.settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT, }; try { if (!window.WebGLRenderingContext) { return false; } var canvas = document.createElement('canvas'); var gl = (canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions)); var success = !!(gl && gl.getContextAttributes().stencil); if (gl) { var loseContext = gl.getExtension('WEBGL_lose_context'); if (loseContext) { loseContext.loseContext(); } } gl = null; return success; } catch (e) { return false; } })(); } return supported; } /** * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0). * * @example * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1] * @memberof PIXI.utils * @function hex2rgb * @param {number} hex - The hexadecimal number to convert * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one * @return {number[]} An array representing the [R, G, B] of the color where all values are floats. */ function hex2rgb(hex, out) { out = out || []; out[0] = ((hex >> 16) & 0xFF) / 255; out[1] = ((hex >> 8) & 0xFF) / 255; out[2] = (hex & 0xFF) / 255; return out; } /** * Converts a hexadecimal color number to a string. * * @example * PIXI.utils.hex2string(0xffffff); // returns "#ffffff" * @memberof PIXI.utils * @function hex2string * @param {number} hex - Number in hex (e.g., `0xffffff`) * @return {string} The string color (e.g., `"#ffffff"`). */ function hex2string(hex) { var hexString = hex.toString(16); hexString = '000000'.substr(0, 6 - hexString.length) + hexString; return "#" + hexString; } /** * Converts a hexadecimal string to a hexadecimal color number. * * @example * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff * @memberof PIXI.utils * @function string2hex * @param {string} The string color (e.g., `"#ffffff"`) * @return {number} Number in hexadecimal. */ function string2hex(string) { if (typeof string === 'string' && string[0] === '#') { string = string.substr(1); } return parseInt(string, 16); } /** * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number. * * @example * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff * @memberof PIXI.utils * @function rgb2hex * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0. * @return {number} Number in hexadecimal. */ function rgb2hex(rgb) { return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0)); } /** * Corrects PixiJS blend, takes premultiplied alpha into account * * @memberof PIXI.utils * @function mapPremultipliedBlendModes * @private * @return {Array} Mapped modes. */ function mapPremultipliedBlendModes() { var pm = []; var npm = []; for (var i = 0; i < 32; i++) { pm[i] = i; npm[i] = i; } pm[constants.BLEND_MODES.NORMAL_NPM] = constants.BLEND_MODES.NORMAL; pm[constants.BLEND_MODES.ADD_NPM] = constants.BLEND_MODES.ADD; pm[constants.BLEND_MODES.SCREEN_NPM] = constants.BLEND_MODES.SCREEN; npm[constants.BLEND_MODES.NORMAL] = constants.BLEND_MODES.NORMAL_NPM; npm[constants.BLEND_MODES.ADD] = constants.BLEND_MODES.ADD_NPM; npm[constants.BLEND_MODES.SCREEN] = constants.BLEND_MODES.SCREEN_NPM; var array = []; array.push(npm); array.push(pm); return array; } /** * maps premultiply flag and blendMode to adjusted blendMode * @memberof PIXI.utils * @const premultiplyBlendMode * @type {Array} */ var premultiplyBlendMode = mapPremultipliedBlendModes(); /** * changes blendMode according to texture format * * @memberof PIXI.utils * @function correctBlendMode * @param {number} blendMode supposed blend mode * @param {boolean} premultiplied whether source is premultiplied * @returns {number} true blend mode for this texture */ function correctBlendMode(blendMode, premultiplied) { return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; } /** * combines rgb and alpha to out array * * @memberof PIXI.utils * @function premultiplyRgba * @param {Float32Array|number[]} rgb input rgb * @param {number} alpha alpha param * @param {Float32Array} [out] output * @param {boolean} [premultiply=true] do premultiply it * @returns {Float32Array} vec4 rgba */ function premultiplyRgba(rgb, alpha, out, premultiply) { out = out || new Float32Array(4); if (premultiply || premultiply === undefined) { out[0] = rgb[0] * alpha; out[1] = rgb[1] * alpha; out[2] = rgb[2] * alpha; } else { out[0] = rgb[0]; out[1] = rgb[1]; out[2] = rgb[2]; } out[3] = alpha; return out; } /** * premultiplies tint * * @memberof PIXI.utils * @function premultiplyTint * @param {number} tint integer RGB * @param {number} alpha floating point alpha (0.0-1.0) * @returns {number} tint multiplied by alpha */ function premultiplyTint(tint, alpha) { if (alpha === 1.0) { return (alpha * 255 << 24) + tint; } if (alpha === 0.0) { return 0; } var R = ((tint >> 16) & 0xFF); var G = ((tint >> 8) & 0xFF); var B = (tint & 0xFF); R = ((R * alpha) + 0.5) | 0; G = ((G * alpha) + 0.5) | 0; B = ((B * alpha) + 0.5) | 0; return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; } /** * converts integer tint and float alpha to vec4 form, premultiplies by default * * @memberof PIXI.utils * @function premultiplyTintToRgba * @param {number} tint input tint * @param {number} alpha alpha param * @param {Float32Array} [out] output * @param {boolean} [premultiply=true] do premultiply it * @returns {Float32Array} vec4 rgba */ function premultiplyTintToRgba(tint, alpha, out, premultiply) { out = out || new Float32Array(4); out[0] = ((tint >> 16) & 0xFF) / 255.0; out[1] = ((tint >> 8) & 0xFF) / 255.0; out[2] = (tint & 0xFF) / 255.0; if (premultiply || premultiply === undefined) { out[0] *= alpha; out[1] *= alpha; out[2] *= alpha; } out[3] = alpha; return out; } /** * Generic Mask Stack data structure * * @memberof PIXI.utils * @function createIndicesForQuads * @param {number} size - Number of quads * @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size` * @return {Uint16Array|Uint32Array} - Resulting index buffer */ function createIndicesForQuads(size, outBuffer) { if (outBuffer === void 0) { outBuffer = null; } // the total number of indices in our array, there are 6 points per quad. var totalIndices = size * 6; outBuffer = outBuffer || new Uint16Array(totalIndices); if (outBuffer.length !== totalIndices) { throw new Error("Out buffer length is incorrect, got " + outBuffer.length + " and expected " + totalIndices); } // fill the indices with the quads to draw for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { outBuffer[i + 0] = j + 0; outBuffer[i + 1] = j + 1; outBuffer[i + 2] = j + 2; outBuffer[i + 3] = j + 0; outBuffer[i + 4] = j + 2; outBuffer[i + 5] = j + 3; } return outBuffer; } function getBufferType(array) { if (array.BYTES_PER_ELEMENT === 4) { if (array instanceof Float32Array) { return 'Float32Array'; } else if (array instanceof Uint32Array) { return 'Uint32Array'; } return 'Int32Array'; } else if (array.BYTES_PER_ELEMENT === 2) { if (array instanceof Uint16Array) { return 'Uint16Array'; } } else if (array.BYTES_PER_ELEMENT === 1) { if (array instanceof Uint8Array) { return 'Uint8Array'; } } // TODO map out the rest of the array elements! return null; } /* eslint-disable object-shorthand */ var map = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array }; function interleaveTypedArrays(arrays, sizes) { var outSize = 0; var stride = 0; var views = {}; for (var i = 0; i < arrays.length; i++) { stride += sizes[i]; outSize += arrays[i].length; } var buffer = new ArrayBuffer(outSize * 4); var out = null; var littleOffset = 0; for (var i = 0; i < arrays.length; i++) { var size = sizes[i]; var array = arrays[i]; /* @todo This is unsafe casting but consistent with how the code worked previously. Should it stay this way or should and `getBufferTypeUnsafe` function be exposed that throws an Error if unsupported type is passed? */ var type = getBufferType(array); if (!views[type]) { views[type] = new map[type](buffer); } out = views[type]; for (var j = 0; j < array.length; j++) { var indexStart = ((j / size | 0) * stride) + littleOffset; var index = j % size; out[indexStart + index] = array[j]; } littleOffset += size; } return new Float32Array(buffer); } // Taken from the bit-twiddle package /** * Rounds to next power of two. * * @function nextPow2 * @memberof PIXI.utils * @param {number} v input value * @return {number} */ function nextPow2(v) { v += v === 0 ? 1 : 0; --v; v |= v >>> 1; v |= v >>> 2; v |= v >>> 4; v |= v >>> 8; v |= v >>> 16; return v + 1; } /** * Checks if a number is a power of two. * * @function isPow2 * @memberof PIXI.utils * @param {number} v input value * @return {boolean} `true` if value is power of two */ function isPow2(v) { return !(v & (v - 1)) && (!!v); } /** * Computes ceil of log base 2 * * @function log2 * @memberof PIXI.utils * @param {number} v input value * @return {number} logarithm base 2 */ function log2(v) { var r = (v > 0xFFFF ? 1 : 0) << 4; v >>>= r; var shift = (v > 0xFF ? 1 : 0) << 3; v >>>= shift; r |= shift; shift = (v > 0xF ? 1 : 0) << 2; v >>>= shift; r |= shift; shift = (v > 0x3 ? 1 : 0) << 1; v >>>= shift; r |= shift; return r | (v >> 1); } /** * Remove items from a javascript array without generating garbage * * @function removeItems * @memberof PIXI.utils * @param {Array} arr Array to remove elements from * @param {number} startIdx starting index * @param {number} removeCount how many to remove */ function removeItems(arr, startIdx, removeCount) { var length = arr.length; var i; if (startIdx >= length || removeCount === 0) { return; } removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount); var len = length - removeCount; for (i = startIdx; i < len; ++i) { arr[i] = arr[i + removeCount]; } arr.length = len; } /** * Returns sign of number * * @memberof PIXI.utils * @function sign * @param {number} n - the number to check the sign of * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive */ function sign(n) { if (n === 0) { return 0; } return n < 0 ? -1 : 1; } var nextUid = 0; /** * Gets the next unique identifier * * @memberof PIXI.utils * @function uid * @return {number} The next unique identifier to use. */ function uid() { return ++nextUid; } // A map of warning messages already fired var warnings = {}; /** * Helper for warning developers about deprecated features & settings. * A stack track for warnings is given; useful for tracking-down where * deprecated methods/properties/classes are being used within the code. * * @memberof PIXI.utils * @function deprecation * @param {string} version - The version where the feature became deprecated * @param {string} message - Message should include what is deprecated, where, and the new solution * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack * this is mostly to ignore internal deprecation calls. */ function deprecation(version, message, ignoreDepth) { if (ignoreDepth === void 0) { ignoreDepth = 3; } // Ignore duplicat if (warnings[message]) { return; } /* eslint-disable no-console */ var stack = new Error().stack; // Handle IE < 10 and Safari < 6 if (typeof stack === 'undefined') { console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); } else { // chop off the stack trace which includes PixiJS internal calls stack = stack.split('\n').splice(ignoreDepth).join('\n'); if (console.groupCollapsed) { console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version); console.warn(stack); console.groupEnd(); } else { console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); console.warn(stack); } } /* eslint-enable no-console */ warnings[message] = true; } /** * @todo Describe property usage * * @static * @name ProgramCache * @memberof PIXI.utils * @type {Object} */ var ProgramCache = {}; /** * @todo Describe property usage * * @static * @name TextureCache * @memberof PIXI.utils * @type {Object} */ var TextureCache = Object.create(null); /** * @todo Describe property usage * * @static * @name BaseTextureCache * @memberof PIXI.utils * @type {Object} */ var BaseTextureCache = Object.create(null); /** * Destroys all texture in the cache * * @memberof PIXI.utils * @function destroyTextureCache */ function destroyTextureCache() { var key; for (key in TextureCache) { TextureCache[key].destroy(); } for (key in BaseTextureCache) { BaseTextureCache[key].destroy(); } } /** * Removes all textures from cache, but does not destroy them * * @memberof PIXI.utils * @function clearTextureCache */ function clearTextureCache() { var key; for (key in TextureCache) { delete TextureCache[key]; } for (key in BaseTextureCache) { delete BaseTextureCache[key]; } } /** * Creates a Canvas element of the given size to be used as a target for rendering to. * * @class * @memberof PIXI.utils */ var CanvasRenderTarget = /** @class */ (function () { /** * @param {number} width - the width for the newly created canvas * @param {number} height - the height for the newly created canvas * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas */ function CanvasRenderTarget(width, height, resolution) { /** * The Canvas object that belongs to this CanvasRenderTarget. * * @member {HTMLCanvasElement} */ this.canvas = document.createElement('canvas'); /** * A CanvasRenderingContext2D object representing a two-dimensional rendering context. * * @member {CanvasRenderingContext2D} */ this.context = this.canvas.getContext('2d'); this.resolution = resolution || settings.settings.RESOLUTION; this.resize(width, height); } /** * Clears the canvas that was created by the CanvasRenderTarget class. * * @private */ CanvasRenderTarget.prototype.clear = function () { this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); }; /** * Resizes the canvas to the specified width and height. * * @param {number} width - the new width of the canvas * @param {number} height - the new height of the canvas */ CanvasRenderTarget.prototype.resize = function (width, height) { this.canvas.width = width * this.resolution; this.canvas.height = height * this.resolution; }; /** * Destroys this canvas. * */ CanvasRenderTarget.prototype.destroy = function () { this.context = null; this.canvas = null; }; Object.defineProperty(CanvasRenderTarget.prototype, "width", { /** * The width of the canvas buffer in pixels. * * @member {number} */ get: function () { return this.canvas.width; }, set: function (val) { this.canvas.width = val; }, enumerable: true, configurable: true }); Object.defineProperty(CanvasRenderTarget.prototype, "height", { /** * The height of the canvas buffer in pixels. * * @member {number} */ get: function () { return this.canvas.height; }, set: function (val) { this.canvas.height = val; }, enumerable: true, configurable: true }); return CanvasRenderTarget; }()); /** * Trim transparent borders from a canvas * * @memberof PIXI.utils * @function trimCanvas * @param {HTMLCanvasElement} canvas - the canvas to trim * @returns {object} Trim data */ function trimCanvas(canvas) { // https://gist.github.com/remy/784508 var width = canvas.width; var height = canvas.height; var context = canvas.getContext('2d'); var imageData = context.getImageData(0, 0, width, height); var pixels = imageData.data; var len = pixels.length; var bound = { top: null, left: null, right: null, bottom: null, }; var data = null; var i; var x; var y; for (i = 0; i < len; i += 4) { if (pixels[i + 3] !== 0) { x = (i / 4) % width; y = ~~((i / 4) / width); if (bound.top === null) { bound.top = y; } if (bound.left === null) { bound.left = x; } else if (x < bound.left) { bound.left = x; } if (bound.right === null) { bound.right = x + 1; } else if (bound.right < x) { bound.right = x + 1; } if (bound.bottom === null) { bound.bottom = y; } else if (bound.bottom < y) { bound.bottom = y; } } } if (bound.top !== null) { width = bound.right - bound.left; height = bound.bottom - bound.top + 1; data = context.getImageData(bound.left, bound.top, width, height); } return { height: height, width: width, data: data, }; } /** * Regexp for data URI. * Based on: {@link https://github.com/ragingwind/data-uri-regex} * * @static * @constant {RegExp|string} DATA_URI * @memberof PIXI * @example data:image/png;base64 */ var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; /** * @memberof PIXI.utils * @interface DecomposedDataUri */ /** * type, eg. `image` * @memberof PIXI.utils.DecomposedDataUri# * @member {string} mediaType */ /** * Sub type, eg. `png` * @memberof PIXI.utils.DecomposedDataUri# * @member {string} subType */ /** * @memberof PIXI.utils.DecomposedDataUri# * @member {string} charset */ /** * Data encoding, eg. `base64` * @memberof PIXI.utils.DecomposedDataUri# * @member {string} encoding */ /** * The actual data * @memberof PIXI.utils.DecomposedDataUri# * @member {string} data */ /** * Split a data URI into components. Returns undefined if * parameter `dataUri` is not a valid data URI. * * @memberof PIXI.utils * @function decomposeDataUri * @param {string} dataUri - the data URI to check * @return {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined */ function decomposeDataUri(dataUri) { var dataUriMatch = DATA_URI.exec(dataUri); if (dataUriMatch) { return { mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, data: dataUriMatch[5], }; } return undefined; } var tempAnchor; /** * Sets the `crossOrigin` property for this resource based on if the url * for this resource is cross-origin. If crossOrigin was manually set, this * function does nothing. * Nipped from the resource loader! * * @ignore * @param {string} url - The url to test. * @param {object} [loc=window.location] - The location object to test against. * @return {string} The crossOrigin value to use (or empty string for none). */ function determineCrossOrigin(url, loc) { if (loc === void 0) { loc = window.location; } // data: and javascript: urls are considered same-origin if (url.indexOf('data:') === 0) { return ''; } // default is window.location loc = loc || window.location; if (!tempAnchor) { tempAnchor = document.createElement('a'); } // let the browser determine the full href for the url of this resource and then // parse with the node url lib, we can't use the properties of the anchor element // because they don't work in IE9 :( tempAnchor.href = url; var parsedUrl = _url.parse(tempAnchor.href); var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); // if cross origin if (parsedUrl.hostname !== loc.hostname || !samePort || parsedUrl.protocol !== loc.protocol) { return 'anonymous'; } return ''; } /** * get the resolution / device pixel ratio of an asset by looking for the prefix * used by spritesheets and image urls * * @memberof PIXI.utils * @function getResolutionOfUrl * @param {string} url - the image path * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. * @return {number} resolution / device pixel ratio of an asset */ function getResolutionOfUrl(url, defaultValue) { var resolution = settings.settings.RETINA_PREFIX.exec(url); if (resolution) { return parseFloat(resolution[1]); } return defaultValue !== undefined ? defaultValue : 1; } /** * Generalized convenience utilities for PIXI. * @example * // Extend PIXI's internal Event Emitter. * class MyEmitter extends PIXI.utils.EventEmitter { * constructor() { * super(); * console.log("Emitter created!"); * } * } * * // Get info on current device * console.log(PIXI.utils.isMobile); * * // Convert hex color to string * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" * @namespace PIXI.utils */ Object.defineProperty(exports, 'isMobile', { enumerable: true, get: function () { return settings.isMobile; } }); exports.EventEmitter = eventemitter3; exports.earcut = earcut; exports.url = _url__default; exports.BaseTextureCache = BaseTextureCache; exports.CanvasRenderTarget = CanvasRenderTarget; exports.DATA_URI = DATA_URI; exports.ProgramCache = ProgramCache; exports.TextureCache = TextureCache; exports.clearTextureCache = clearTextureCache; exports.correctBlendMode = correctBlendMode; exports.createIndicesForQuads = createIndicesForQuads; exports.decomposeDataUri = decomposeDataUri; exports.deprecation = deprecation; exports.destroyTextureCache = destroyTextureCache; exports.determineCrossOrigin = determineCrossOrigin; exports.getBufferType = getBufferType; exports.getResolutionOfUrl = getResolutionOfUrl; exports.hex2rgb = hex2rgb; exports.hex2string = hex2string; exports.interleaveTypedArrays = interleaveTypedArrays; exports.isPow2 = isPow2; exports.isWebGLSupported = isWebGLSupported; exports.log2 = log2; exports.nextPow2 = nextPow2; exports.premultiplyBlendMode = premultiplyBlendMode; exports.premultiplyRgba = premultiplyRgba; exports.premultiplyTint = premultiplyTint; exports.premultiplyTintToRgba = premultiplyTintToRgba; exports.removeItems = removeItems; exports.rgb2hex = rgb2hex; exports.sayHello = sayHello; exports.sign = sign; exports.skipHello = skipHello; exports.string2hex = string2hex; exports.trimCanvas = trimCanvas; exports.uid = uid; },{"@pixi/constants":6,"@pixi/settings":31,"earcut":51,"eventemitter3":53,"url":396}],40:[function(require,module,exports){ /** * Extend function * ================ * * Function used to push a bunch of values into an array at once. * * Its strategy is to mutate target array's length then setting the new indices * to be the values to add. * * A benchmark proved that it is faster than the following strategies: * 1) `array.push.apply(array, values)`. * 2) A loop of pushes. * 3) `array = array.concat(values)`, obviously. * * Intuitively, this is correct because when adding a lot of elements, the * chosen strategies does not need to handle the `arguments` object to * execute #.apply's variadicity and because the array know its final length * at the beginning, avoiding potential multiple reallocations of the underlying * contiguous array. Some engines may be able to optimize the loop of push * operations but empirically they don't seem to do so. */ /** * Extends the target array with the given values. * * @param {array} array - Target array. * @param {array} values - Values to add. */ module.exports = function extend(array, values) { var l2 = values.length; if (l2 === 0) return; var l1 = array.length; array.length += l2; for (var i = 0; i < l2; i++) array[l1 + i] = values[i]; }; },{}],41:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function getLens (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk( uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) )) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } },{}],42:[function(require,module,exports){ },{}],43:[function(require,module,exports){ (function (global){ /*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's state to , // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.4.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define('punycode', function() { return punycode; }); } else if (freeExports && freeModule) { if (module.exports == freeExports) { // in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports = punycode; } else { // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { // in Rhino or a web browser root.punycode = punycode; } }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],44:[function(require,module,exports){ (function (Buffer){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' ) } function typedArraySupport () { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } return arr.foo() === 42 } catch (e) { return false } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.buffer } }) Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.byteOffset } }) function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"') } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length) buf.__proto__ = Buffer.prototype return buf } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError( 'The "string" argument must be of type string. Received type number' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset) } if (ArrayBuffer.isView(value)) { return fromArrayLike(value) } if (value == null) { throw TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } if (isInstance(value, ArrayBuffer) || (value && isInstance(value.buffer, ArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'number') { throw new TypeError( 'The "value" argument must not be of type number. Received type number' ) } var valueOf = value.valueOf && value.valueOf() if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length) } var b = fromObject(value) if (b) return b if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { return Buffer.from( value[Symbol.toPrimitive]('string'), encodingOrOffset, length ) } throw new TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number') } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } var length = byteLength(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayBuffer (array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds') } var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 var buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return b != null && b._isBuffer === true && b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false } Buffer.compare = function compare (a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError( 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' ) } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (isInstance(buf, Uint8Array)) { buf = Buffer.from(buf) } if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { throw new TypeError( 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string ) } var len = string.length var mustMatch = (arguments.length > 2 && arguments[2] === true) if (!mustMatch && len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 } encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.toLocaleString = Buffer.prototype.toString Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() if (this.length > max) str += ' ... ' return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength) } if (!Buffer.isBuffer(target)) { throw new TypeError( 'The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + (typeof target) ) } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } var strLen = string.length if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (numberIsNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0 if (isFinite(length)) { length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf = this.subarray(start, end) // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('Index out of range') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end) } else if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, end), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } if (val.length === 1) { var code = val.charCodeAt(0) if ((encoding === 'utf8' && code < 128) || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code } } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding) var len = bytes.length if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"') } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0] // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance (obj, type) { return obj instanceof type || (obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name) } function numberIsNaN (obj) { // For IE11 support return obj !== obj // eslint-disable-line no-self-compare } }).call(this,require("buffer").Buffer) },{"base64-js":41,"buffer":44,"ieee754":112}],45:[function(require,module,exports){ /** * chroma.js - JavaScript library for color conversions * * Copyright (c) 2011-2019, Gregor Aisch * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name Gregor Aisch may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ------------------------------------------------------- * * chroma.js includes colors from colorbrewer2.org, which are released under * the following license: * * Copyright (c) 2002 Cynthia Brewer, Mark Harrower, * and The Pennsylvania State University. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * * ------------------------------------------------------ * * Named colors are taken from X11 Color Names. * http://www.w3.org/TR/css3-color/#svg-color * * @preserve */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.chroma = factory()); }(this, (function () { 'use strict'; var limit = function (x, min, max) { if ( min === void 0 ) min=0; if ( max === void 0 ) max=1; return x < min ? min : x > max ? max : x; }; var clip_rgb = function (rgb) { rgb._clipped = false; rgb._unclipped = rgb.slice(0); for (var i=0; i<=3; i++) { if (i < 3) { if (rgb[i] < 0 || rgb[i] > 255) { rgb._clipped = true; } rgb[i] = limit(rgb[i], 0, 255); } else if (i === 3) { rgb[i] = limit(rgb[i], 0, 1); } } return rgb; }; // ported from jQuery's $.type var classToType = {}; for (var i = 0, list = ['Boolean', 'Number', 'String', 'Function', 'Array', 'Date', 'RegExp', 'Undefined', 'Null']; i < list.length; i += 1) { var name = list[i]; classToType[("[object " + name + "]")] = name.toLowerCase(); } var type = function(obj) { return classToType[Object.prototype.toString.call(obj)] || "object"; }; var unpack = function (args, keyOrder) { if ( keyOrder === void 0 ) keyOrder=null; // if called with more than 3 arguments, we return the arguments if (args.length >= 3) { return Array.prototype.slice.call(args); } // with less than 3 args we check if first arg is object // and use the keyOrder string to extract and sort properties if (type(args[0]) == 'object' && keyOrder) { return keyOrder.split('') .filter(function (k) { return args[0][k] !== undefined; }) .map(function (k) { return args[0][k]; }); } // otherwise we just return the first argument // (which we suppose is an array of args) return args[0]; }; var last = function (args) { if (args.length < 2) { return null; } var l = args.length-1; if (type(args[l]) == 'string') { return args[l].toLowerCase(); } return null; }; var PI = Math.PI; var utils = { clip_rgb: clip_rgb, limit: limit, type: type, unpack: unpack, last: last, PI: PI, TWOPI: PI*2, PITHIRD: PI/3, DEG2RAD: PI / 180, RAD2DEG: 180 / PI }; var input = { format: {}, autodetect: [] }; var last$1 = utils.last; var clip_rgb$1 = utils.clip_rgb; var type$1 = utils.type; var Color = function Color() { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var me = this; if (type$1(args[0]) === 'object' && args[0].constructor && args[0].constructor === this.constructor) { // the argument is already a Color instance return args[0]; } // last argument could be the mode var mode = last$1(args); var autodetect = false; if (!mode) { autodetect = true; if (!input.sorted) { input.autodetect = input.autodetect.sort(function (a,b) { return b.p - a.p; }); input.sorted = true; } // auto-detect format for (var i = 0, list = input.autodetect; i < list.length; i += 1) { var chk = list[i]; mode = chk.test.apply(chk, args); if (mode) { break; } } } if (input.format[mode]) { var rgb = input.format[mode].apply(null, autodetect ? args : args.slice(0,-1)); me._rgb = clip_rgb$1(rgb); } else { throw new Error('unknown format: '+args); } // add alpha channel if (me._rgb.length === 3) { me._rgb.push(1); } }; Color.prototype.toString = function toString () { if (type$1(this.hex) == 'function') { return this.hex(); } return ("[" + (this._rgb.join(',')) + "]"); }; var Color_1 = Color; var chroma = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( chroma.Color, [ null ].concat( args) )); }; chroma.Color = Color_1; chroma.version = '2.1.0'; var chroma_1 = chroma; var unpack$1 = utils.unpack; var max = Math.max; var rgb2cmyk = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var ref = unpack$1(args, 'rgb'); var r = ref[0]; var g = ref[1]; var b = ref[2]; r = r / 255; g = g / 255; b = b / 255; var k = 1 - max(r,max(g,b)); var f = k < 1 ? 1 / (1-k) : 0; var c = (1-r-k) * f; var m = (1-g-k) * f; var y = (1-b-k) * f; return [c,m,y,k]; }; var rgb2cmyk_1 = rgb2cmyk; var unpack$2 = utils.unpack; var cmyk2rgb = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$2(args, 'cmyk'); var c = args[0]; var m = args[1]; var y = args[2]; var k = args[3]; var alpha = args.length > 4 ? args[4] : 1; if (k === 1) { return [0,0,0,alpha]; } return [ c >= 1 ? 0 : 255 * (1-c) * (1-k), // r m >= 1 ? 0 : 255 * (1-m) * (1-k), // g y >= 1 ? 0 : 255 * (1-y) * (1-k), // b alpha ]; }; var cmyk2rgb_1 = cmyk2rgb; var unpack$3 = utils.unpack; var type$2 = utils.type; Color_1.prototype.cmyk = function() { return rgb2cmyk_1(this._rgb); }; chroma_1.cmyk = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['cmyk']) )); }; input.format.cmyk = cmyk2rgb_1; input.autodetect.push({ p: 2, test: function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$3(args, 'cmyk'); if (type$2(args) === 'array' && args.length === 4) { return 'cmyk'; } } }); var unpack$4 = utils.unpack; var last$2 = utils.last; var rnd = function (a) { return Math.round(a*100)/100; }; /* * supported arguments: * - hsl2css(h,s,l) * - hsl2css(h,s,l,a) * - hsl2css([h,s,l], mode) * - hsl2css([h,s,l,a], mode) * - hsl2css({h,s,l,a}, mode) */ var hsl2css = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var hsla = unpack$4(args, 'hsla'); var mode = last$2(args) || 'lsa'; hsla[0] = rnd(hsla[0] || 0); hsla[1] = rnd(hsla[1]*100) + '%'; hsla[2] = rnd(hsla[2]*100) + '%'; if (mode === 'hsla' || (hsla.length > 3 && hsla[3]<1)) { hsla[3] = hsla.length > 3 ? hsla[3] : 1; mode = 'hsla'; } else { hsla.length = 3; } return (mode + "(" + (hsla.join(',')) + ")"); }; var hsl2css_1 = hsl2css; var unpack$5 = utils.unpack; /* * supported arguments: * - rgb2hsl(r,g,b) * - rgb2hsl(r,g,b,a) * - rgb2hsl([r,g,b]) * - rgb2hsl([r,g,b,a]) * - rgb2hsl({r,g,b,a}) */ var rgb2hsl = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$5(args, 'rgba'); var r = args[0]; var g = args[1]; var b = args[2]; r /= 255; g /= 255; b /= 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var l = (max + min) / 2; var s, h; if (max === min){ s = 0; h = Number.NaN; } else { s = l < 0.5 ? (max - min) / (max + min) : (max - min) / (2 - max - min); } if (r == max) { h = (g - b) / (max - min); } else if (g == max) { h = 2 + (b - r) / (max - min); } else if (b == max) { h = 4 + (r - g) / (max - min); } h *= 60; if (h < 0) { h += 360; } if (args.length>3 && args[3]!==undefined) { return [h,s,l,args[3]]; } return [h,s,l]; }; var rgb2hsl_1 = rgb2hsl; var unpack$6 = utils.unpack; var last$3 = utils.last; var round = Math.round; /* * supported arguments: * - rgb2css(r,g,b) * - rgb2css(r,g,b,a) * - rgb2css([r,g,b], mode) * - rgb2css([r,g,b,a], mode) * - rgb2css({r,g,b,a}, mode) */ var rgb2css = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var rgba = unpack$6(args, 'rgba'); var mode = last$3(args) || 'rgb'; if (mode.substr(0,3) == 'hsl') { return hsl2css_1(rgb2hsl_1(rgba), mode); } rgba[0] = round(rgba[0]); rgba[1] = round(rgba[1]); rgba[2] = round(rgba[2]); if (mode === 'rgba' || (rgba.length > 3 && rgba[3]<1)) { rgba[3] = rgba.length > 3 ? rgba[3] : 1; mode = 'rgba'; } return (mode + "(" + (rgba.slice(0,mode==='rgb'?3:4).join(',')) + ")"); }; var rgb2css_1 = rgb2css; var unpack$7 = utils.unpack; var round$1 = Math.round; var hsl2rgb = function () { var assign; var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$7(args, 'hsl'); var h = args[0]; var s = args[1]; var l = args[2]; var r,g,b; if (s === 0) { r = g = b = l*255; } else { var t3 = [0,0,0]; var c = [0,0,0]; var t2 = l < 0.5 ? l * (1+s) : l+s-l*s; var t1 = 2 * l - t2; var h_ = h / 360; t3[0] = h_ + 1/3; t3[1] = h_; t3[2] = h_ - 1/3; for (var i=0; i<3; i++) { if (t3[i] < 0) { t3[i] += 1; } if (t3[i] > 1) { t3[i] -= 1; } if (6 * t3[i] < 1) { c[i] = t1 + (t2 - t1) * 6 * t3[i]; } else if (2 * t3[i] < 1) { c[i] = t2; } else if (3 * t3[i] < 2) { c[i] = t1 + (t2 - t1) * ((2 / 3) - t3[i]) * 6; } else { c[i] = t1; } } (assign = [round$1(c[0]*255),round$1(c[1]*255),round$1(c[2]*255)], r = assign[0], g = assign[1], b = assign[2]); } if (args.length > 3) { // keep alpha channel return [r,g,b,args[3]]; } return [r,g,b,1]; }; var hsl2rgb_1 = hsl2rgb; var RE_RGB = /^rgb\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*\)$/; var RE_RGBA = /^rgba\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*([01]|[01]?\.\d+)\)$/; var RE_RGB_PCT = /^rgb\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/; var RE_RGBA_PCT = /^rgba\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/; var RE_HSL = /^hsl\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/; var RE_HSLA = /^hsla\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/; var round$2 = Math.round; var css2rgb = function (css) { css = css.toLowerCase().trim(); var m; if (input.format.named) { try { return input.format.named(css); } catch (e) { // eslint-disable-next-line } } // rgb(250,20,0) if ((m = css.match(RE_RGB))) { var rgb = m.slice(1,4); for (var i=0; i<3; i++) { rgb[i] = +rgb[i]; } rgb[3] = 1; // default alpha return rgb; } // rgba(250,20,0,0.4) if ((m = css.match(RE_RGBA))) { var rgb$1 = m.slice(1,5); for (var i$1=0; i$1<4; i$1++) { rgb$1[i$1] = +rgb$1[i$1]; } return rgb$1; } // rgb(100%,0%,0%) if ((m = css.match(RE_RGB_PCT))) { var rgb$2 = m.slice(1,4); for (var i$2=0; i$2<3; i$2++) { rgb$2[i$2] = round$2(rgb$2[i$2] * 2.55); } rgb$2[3] = 1; // default alpha return rgb$2; } // rgba(100%,0%,0%,0.4) if ((m = css.match(RE_RGBA_PCT))) { var rgb$3 = m.slice(1,5); for (var i$3=0; i$3<3; i$3++) { rgb$3[i$3] = round$2(rgb$3[i$3] * 2.55); } rgb$3[3] = +rgb$3[3]; return rgb$3; } // hsl(0,100%,50%) if ((m = css.match(RE_HSL))) { var hsl = m.slice(1,4); hsl[1] *= 0.01; hsl[2] *= 0.01; var rgb$4 = hsl2rgb_1(hsl); rgb$4[3] = 1; return rgb$4; } // hsla(0,100%,50%,0.5) if ((m = css.match(RE_HSLA))) { var hsl$1 = m.slice(1,4); hsl$1[1] *= 0.01; hsl$1[2] *= 0.01; var rgb$5 = hsl2rgb_1(hsl$1); rgb$5[3] = +m[4]; // default alpha = 1 return rgb$5; } }; css2rgb.test = function (s) { return RE_RGB.test(s) || RE_RGBA.test(s) || RE_RGB_PCT.test(s) || RE_RGBA_PCT.test(s) || RE_HSL.test(s) || RE_HSLA.test(s); }; var css2rgb_1 = css2rgb; var type$3 = utils.type; Color_1.prototype.css = function(mode) { return rgb2css_1(this._rgb, mode); }; chroma_1.css = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['css']) )); }; input.format.css = css2rgb_1; input.autodetect.push({ p: 5, test: function (h) { var rest = [], len = arguments.length - 1; while ( len-- > 0 ) rest[ len ] = arguments[ len + 1 ]; if (!rest.length && type$3(h) === 'string' && css2rgb_1.test(h)) { return 'css'; } } }); var unpack$8 = utils.unpack; input.format.gl = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var rgb = unpack$8(args, 'rgba'); rgb[0] *= 255; rgb[1] *= 255; rgb[2] *= 255; return rgb; }; chroma_1.gl = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['gl']) )); }; Color_1.prototype.gl = function() { var rgb = this._rgb; return [rgb[0]/255, rgb[1]/255, rgb[2]/255, rgb[3]]; }; var unpack$9 = utils.unpack; var rgb2hcg = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var ref = unpack$9(args, 'rgb'); var r = ref[0]; var g = ref[1]; var b = ref[2]; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var delta = max - min; var c = delta * 100 / 255; var _g = min / (255 - delta) * 100; var h; if (delta === 0) { h = Number.NaN; } else { if (r === max) { h = (g - b) / delta; } if (g === max) { h = 2+(b - r) / delta; } if (b === max) { h = 4+(r - g) / delta; } h *= 60; if (h < 0) { h += 360; } } return [h, c, _g]; }; var rgb2hcg_1 = rgb2hcg; var unpack$a = utils.unpack; var floor = Math.floor; /* * this is basically just HSV with some minor tweaks * * hue.. [0..360] * chroma .. [0..1] * grayness .. [0..1] */ var hcg2rgb = function () { var assign, assign$1, assign$2, assign$3, assign$4, assign$5; var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$a(args, 'hcg'); var h = args[0]; var c = args[1]; var _g = args[2]; var r,g,b; _g = _g * 255; var _c = c * 255; if (c === 0) { r = g = b = _g; } else { if (h === 360) { h = 0; } if (h > 360) { h -= 360; } if (h < 0) { h += 360; } h /= 60; var i = floor(h); var f = h - i; var p = _g * (1 - c); var q = p + _c * (1 - f); var t = p + _c * f; var v = p + _c; switch (i) { case 0: (assign = [v, t, p], r = assign[0], g = assign[1], b = assign[2]); break case 1: (assign$1 = [q, v, p], r = assign$1[0], g = assign$1[1], b = assign$1[2]); break case 2: (assign$2 = [p, v, t], r = assign$2[0], g = assign$2[1], b = assign$2[2]); break case 3: (assign$3 = [p, q, v], r = assign$3[0], g = assign$3[1], b = assign$3[2]); break case 4: (assign$4 = [t, p, v], r = assign$4[0], g = assign$4[1], b = assign$4[2]); break case 5: (assign$5 = [v, p, q], r = assign$5[0], g = assign$5[1], b = assign$5[2]); break } } return [r, g, b, args.length > 3 ? args[3] : 1]; }; var hcg2rgb_1 = hcg2rgb; var unpack$b = utils.unpack; var type$4 = utils.type; Color_1.prototype.hcg = function() { return rgb2hcg_1(this._rgb); }; chroma_1.hcg = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hcg']) )); }; input.format.hcg = hcg2rgb_1; input.autodetect.push({ p: 1, test: function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$b(args, 'hcg'); if (type$4(args) === 'array' && args.length === 3) { return 'hcg'; } } }); var unpack$c = utils.unpack; var last$4 = utils.last; var round$3 = Math.round; var rgb2hex = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var ref = unpack$c(args, 'rgba'); var r = ref[0]; var g = ref[1]; var b = ref[2]; var a = ref[3]; var mode = last$4(args) || 'auto'; if (a === undefined) { a = 1; } if (mode === 'auto') { mode = a < 1 ? 'rgba' : 'rgb'; } r = round$3(r); g = round$3(g); b = round$3(b); var u = r << 16 | g << 8 | b; var str = "000000" + u.toString(16); //#.toUpperCase(); str = str.substr(str.length - 6); var hxa = '0' + round$3(a * 255).toString(16); hxa = hxa.substr(hxa.length - 2); switch (mode.toLowerCase()) { case 'rgba': return ("#" + str + hxa); case 'argb': return ("#" + hxa + str); default: return ("#" + str); } }; var rgb2hex_1 = rgb2hex; var RE_HEX = /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/; var RE_HEXA = /^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{4})$/; var hex2rgb = function (hex) { if (hex.match(RE_HEX)) { // remove optional leading # if (hex.length === 4 || hex.length === 7) { hex = hex.substr(1); } // expand short-notation to full six-digit if (hex.length === 3) { hex = hex.split(''); hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]; } var u = parseInt(hex, 16); var r = u >> 16; var g = u >> 8 & 0xFF; var b = u & 0xFF; return [r,g,b,1]; } // match rgba hex format, eg #FF000077 if (hex.match(RE_HEXA)) { if (hex.length === 5 || hex.length === 9) { // remove optional leading # hex = hex.substr(1); } // expand short-notation to full eight-digit if (hex.length === 4) { hex = hex.split(''); hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]+hex[3]+hex[3]; } var u$1 = parseInt(hex, 16); var r$1 = u$1 >> 24 & 0xFF; var g$1 = u$1 >> 16 & 0xFF; var b$1 = u$1 >> 8 & 0xFF; var a = Math.round((u$1 & 0xFF) / 0xFF * 100) / 100; return [r$1,g$1,b$1,a]; } // we used to check for css colors here // if _input.css? and rgb = _input.css hex // return rgb throw new Error(("unknown hex color: " + hex)); }; var hex2rgb_1 = hex2rgb; var type$5 = utils.type; Color_1.prototype.hex = function(mode) { return rgb2hex_1(this._rgb, mode); }; chroma_1.hex = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hex']) )); }; input.format.hex = hex2rgb_1; input.autodetect.push({ p: 4, test: function (h) { var rest = [], len = arguments.length - 1; while ( len-- > 0 ) rest[ len ] = arguments[ len + 1 ]; if (!rest.length && type$5(h) === 'string' && [3,4,5,6,7,8,9].indexOf(h.length) >= 0) { return 'hex'; } } }); var unpack$d = utils.unpack; var TWOPI = utils.TWOPI; var min = Math.min; var sqrt = Math.sqrt; var acos = Math.acos; var rgb2hsi = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; /* borrowed from here: http://hummer.stanford.edu/museinfo/doc/examples/humdrum/keyscape2/rgb2hsi.cpp */ var ref = unpack$d(args, 'rgb'); var r = ref[0]; var g = ref[1]; var b = ref[2]; r /= 255; g /= 255; b /= 255; var h; var min_ = min(r,g,b); var i = (r+g+b) / 3; var s = i > 0 ? 1 - min_/i : 0; if (s === 0) { h = NaN; } else { h = ((r-g)+(r-b)) / 2; h /= sqrt((r-g)*(r-g) + (r-b)*(g-b)); h = acos(h); if (b > g) { h = TWOPI - h; } h /= TWOPI; } return [h*360,s,i]; }; var rgb2hsi_1 = rgb2hsi; var unpack$e = utils.unpack; var limit$1 = utils.limit; var TWOPI$1 = utils.TWOPI; var PITHIRD = utils.PITHIRD; var cos = Math.cos; /* * hue [0..360] * saturation [0..1] * intensity [0..1] */ var hsi2rgb = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; /* borrowed from here: http://hummer.stanford.edu/museinfo/doc/examples/humdrum/keyscape2/hsi2rgb.cpp */ args = unpack$e(args, 'hsi'); var h = args[0]; var s = args[1]; var i = args[2]; var r,g,b; if (isNaN(h)) { h = 0; } if (isNaN(s)) { s = 0; } // normalize hue if (h > 360) { h -= 360; } if (h < 0) { h += 360; } h /= 360; if (h < 1/3) { b = (1-s)/3; r = (1+s*cos(TWOPI$1*h)/cos(PITHIRD-TWOPI$1*h))/3; g = 1 - (b+r); } else if (h < 2/3) { h -= 1/3; r = (1-s)/3; g = (1+s*cos(TWOPI$1*h)/cos(PITHIRD-TWOPI$1*h))/3; b = 1 - (r+g); } else { h -= 2/3; g = (1-s)/3; b = (1+s*cos(TWOPI$1*h)/cos(PITHIRD-TWOPI$1*h))/3; r = 1 - (g+b); } r = limit$1(i*r*3); g = limit$1(i*g*3); b = limit$1(i*b*3); return [r*255, g*255, b*255, args.length > 3 ? args[3] : 1]; }; var hsi2rgb_1 = hsi2rgb; var unpack$f = utils.unpack; var type$6 = utils.type; Color_1.prototype.hsi = function() { return rgb2hsi_1(this._rgb); }; chroma_1.hsi = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hsi']) )); }; input.format.hsi = hsi2rgb_1; input.autodetect.push({ p: 2, test: function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$f(args, 'hsi'); if (type$6(args) === 'array' && args.length === 3) { return 'hsi'; } } }); var unpack$g = utils.unpack; var type$7 = utils.type; Color_1.prototype.hsl = function() { return rgb2hsl_1(this._rgb); }; chroma_1.hsl = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hsl']) )); }; input.format.hsl = hsl2rgb_1; input.autodetect.push({ p: 2, test: function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$g(args, 'hsl'); if (type$7(args) === 'array' && args.length === 3) { return 'hsl'; } } }); var unpack$h = utils.unpack; var min$1 = Math.min; var max$1 = Math.max; /* * supported arguments: * - rgb2hsv(r,g,b) * - rgb2hsv([r,g,b]) * - rgb2hsv({r,g,b}) */ var rgb2hsl$1 = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$h(args, 'rgb'); var r = args[0]; var g = args[1]; var b = args[2]; var min_ = min$1(r, g, b); var max_ = max$1(r, g, b); var delta = max_ - min_; var h,s,v; v = max_ / 255.0; if (max_ === 0) { h = Number.NaN; s = 0; } else { s = delta / max_; if (r === max_) { h = (g - b) / delta; } if (g === max_) { h = 2+(b - r) / delta; } if (b === max_) { h = 4+(r - g) / delta; } h *= 60; if (h < 0) { h += 360; } } return [h, s, v] }; var rgb2hsv = rgb2hsl$1; var unpack$i = utils.unpack; var floor$1 = Math.floor; var hsv2rgb = function () { var assign, assign$1, assign$2, assign$3, assign$4, assign$5; var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$i(args, 'hsv'); var h = args[0]; var s = args[1]; var v = args[2]; var r,g,b; v *= 255; if (s === 0) { r = g = b = v; } else { if (h === 360) { h = 0; } if (h > 360) { h -= 360; } if (h < 0) { h += 360; } h /= 60; var i = floor$1(h); var f = h - i; var p = v * (1 - s); var q = v * (1 - s * f); var t = v * (1 - s * (1 - f)); switch (i) { case 0: (assign = [v, t, p], r = assign[0], g = assign[1], b = assign[2]); break case 1: (assign$1 = [q, v, p], r = assign$1[0], g = assign$1[1], b = assign$1[2]); break case 2: (assign$2 = [p, v, t], r = assign$2[0], g = assign$2[1], b = assign$2[2]); break case 3: (assign$3 = [p, q, v], r = assign$3[0], g = assign$3[1], b = assign$3[2]); break case 4: (assign$4 = [t, p, v], r = assign$4[0], g = assign$4[1], b = assign$4[2]); break case 5: (assign$5 = [v, p, q], r = assign$5[0], g = assign$5[1], b = assign$5[2]); break } } return [r,g,b,args.length > 3?args[3]:1]; }; var hsv2rgb_1 = hsv2rgb; var unpack$j = utils.unpack; var type$8 = utils.type; Color_1.prototype.hsv = function() { return rgb2hsv(this._rgb); }; chroma_1.hsv = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hsv']) )); }; input.format.hsv = hsv2rgb_1; input.autodetect.push({ p: 2, test: function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$j(args, 'hsv'); if (type$8(args) === 'array' && args.length === 3) { return 'hsv'; } } }); var labConstants = { // Corresponds roughly to RGB brighter/darker Kn: 18, // D65 standard referent Xn: 0.950470, Yn: 1, Zn: 1.088830, t0: 0.137931034, // 4 / 29 t1: 0.206896552, // 6 / 29 t2: 0.12841855, // 3 * t1 * t1 t3: 0.008856452, // t1 * t1 * t1 }; var unpack$k = utils.unpack; var pow = Math.pow; var rgb2lab = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var ref = unpack$k(args, 'rgb'); var r = ref[0]; var g = ref[1]; var b = ref[2]; var ref$1 = rgb2xyz(r,g,b); var x = ref$1[0]; var y = ref$1[1]; var z = ref$1[2]; var l = 116 * y - 16; return [l < 0 ? 0 : l, 500 * (x - y), 200 * (y - z)]; }; var rgb_xyz = function (r) { if ((r /= 255) <= 0.04045) { return r / 12.92; } return pow((r + 0.055) / 1.055, 2.4); }; var xyz_lab = function (t) { if (t > labConstants.t3) { return pow(t, 1 / 3); } return t / labConstants.t2 + labConstants.t0; }; var rgb2xyz = function (r,g,b) { r = rgb_xyz(r); g = rgb_xyz(g); b = rgb_xyz(b); var x = xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / labConstants.Xn); var y = xyz_lab((0.2126729 * r + 0.7151522 * g + 0.0721750 * b) / labConstants.Yn); var z = xyz_lab((0.0193339 * r + 0.1191920 * g + 0.9503041 * b) / labConstants.Zn); return [x,y,z]; }; var rgb2lab_1 = rgb2lab; var unpack$l = utils.unpack; var pow$1 = Math.pow; /* * L* [0..100] * a [-100..100] * b [-100..100] */ var lab2rgb = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$l(args, 'lab'); var l = args[0]; var a = args[1]; var b = args[2]; var x,y,z, r,g,b_; y = (l + 16) / 116; x = isNaN(a) ? y : y + a / 500; z = isNaN(b) ? y : y - b / 200; y = labConstants.Yn * lab_xyz(y); x = labConstants.Xn * lab_xyz(x); z = labConstants.Zn * lab_xyz(z); r = xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z); // D65 -> sRGB g = xyz_rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z); b_ = xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z); return [r,g,b_,args.length > 3 ? args[3] : 1]; }; var xyz_rgb = function (r) { return 255 * (r <= 0.00304 ? 12.92 * r : 1.055 * pow$1(r, 1 / 2.4) - 0.055) }; var lab_xyz = function (t) { return t > labConstants.t1 ? t * t * t : labConstants.t2 * (t - labConstants.t0) }; var lab2rgb_1 = lab2rgb; var unpack$m = utils.unpack; var type$9 = utils.type; Color_1.prototype.lab = function() { return rgb2lab_1(this._rgb); }; chroma_1.lab = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['lab']) )); }; input.format.lab = lab2rgb_1; input.autodetect.push({ p: 2, test: function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$m(args, 'lab'); if (type$9(args) === 'array' && args.length === 3) { return 'lab'; } } }); var unpack$n = utils.unpack; var RAD2DEG = utils.RAD2DEG; var sqrt$1 = Math.sqrt; var atan2 = Math.atan2; var round$4 = Math.round; var lab2lch = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var ref = unpack$n(args, 'lab'); var l = ref[0]; var a = ref[1]; var b = ref[2]; var c = sqrt$1(a * a + b * b); var h = (atan2(b, a) * RAD2DEG + 360) % 360; if (round$4(c*10000) === 0) { h = Number.NaN; } return [l, c, h]; }; var lab2lch_1 = lab2lch; var unpack$o = utils.unpack; var rgb2lch = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var ref = unpack$o(args, 'rgb'); var r = ref[0]; var g = ref[1]; var b = ref[2]; var ref$1 = rgb2lab_1(r,g,b); var l = ref$1[0]; var a = ref$1[1]; var b_ = ref$1[2]; return lab2lch_1(l,a,b_); }; var rgb2lch_1 = rgb2lch; var unpack$p = utils.unpack; var DEG2RAD = utils.DEG2RAD; var sin = Math.sin; var cos$1 = Math.cos; var lch2lab = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; /* Convert from a qualitative parameter h and a quantitative parameter l to a 24-bit pixel. These formulas were invented by David Dalrymple to obtain maximum contrast without going out of gamut if the parameters are in the range 0-1. A saturation multiplier was added by Gregor Aisch */ var ref = unpack$p(args, 'lch'); var l = ref[0]; var c = ref[1]; var h = ref[2]; if (isNaN(h)) { h = 0; } h = h * DEG2RAD; return [l, cos$1(h) * c, sin(h) * c] }; var lch2lab_1 = lch2lab; var unpack$q = utils.unpack; var lch2rgb = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$q(args, 'lch'); var l = args[0]; var c = args[1]; var h = args[2]; var ref = lch2lab_1 (l,c,h); var L = ref[0]; var a = ref[1]; var b_ = ref[2]; var ref$1 = lab2rgb_1 (L,a,b_); var r = ref$1[0]; var g = ref$1[1]; var b = ref$1[2]; return [r, g, b, args.length > 3 ? args[3] : 1]; }; var lch2rgb_1 = lch2rgb; var unpack$r = utils.unpack; var hcl2rgb = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var hcl = unpack$r(args, 'hcl').reverse(); return lch2rgb_1.apply(void 0, hcl); }; var hcl2rgb_1 = hcl2rgb; var unpack$s = utils.unpack; var type$a = utils.type; Color_1.prototype.lch = function() { return rgb2lch_1(this._rgb); }; Color_1.prototype.hcl = function() { return rgb2lch_1(this._rgb).reverse(); }; chroma_1.lch = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['lch']) )); }; chroma_1.hcl = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hcl']) )); }; input.format.lch = lch2rgb_1; input.format.hcl = hcl2rgb_1; ['lch','hcl'].forEach(function (m) { return input.autodetect.push({ p: 2, test: function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$s(args, m); if (type$a(args) === 'array' && args.length === 3) { return m; } } }); }); /** X11 color names http://www.w3.org/TR/css3-color/#svg-color */ var w3cx11 = { aliceblue: '#f0f8ff', antiquewhite: '#faebd7', aqua: '#00ffff', aquamarine: '#7fffd4', azure: '#f0ffff', beige: '#f5f5dc', bisque: '#ffe4c4', black: '#000000', blanchedalmond: '#ffebcd', blue: '#0000ff', blueviolet: '#8a2be2', brown: '#a52a2a', burlywood: '#deb887', cadetblue: '#5f9ea0', chartreuse: '#7fff00', chocolate: '#d2691e', coral: '#ff7f50', cornflower: '#6495ed', cornflowerblue: '#6495ed', cornsilk: '#fff8dc', crimson: '#dc143c', cyan: '#00ffff', darkblue: '#00008b', darkcyan: '#008b8b', darkgoldenrod: '#b8860b', darkgray: '#a9a9a9', darkgreen: '#006400', darkgrey: '#a9a9a9', darkkhaki: '#bdb76b', darkmagenta: '#8b008b', darkolivegreen: '#556b2f', darkorange: '#ff8c00', darkorchid: '#9932cc', darkred: '#8b0000', darksalmon: '#e9967a', darkseagreen: '#8fbc8f', darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkslategrey: '#2f4f4f', darkturquoise: '#00ced1', darkviolet: '#9400d3', deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1e90ff', firebrick: '#b22222', floralwhite: '#fffaf0', forestgreen: '#228b22', fuchsia: '#ff00ff', gainsboro: '#dcdcdc', ghostwhite: '#f8f8ff', gold: '#ffd700', goldenrod: '#daa520', gray: '#808080', green: '#008000', greenyellow: '#adff2f', grey: '#808080', honeydew: '#f0fff0', hotpink: '#ff69b4', indianred: '#cd5c5c', indigo: '#4b0082', ivory: '#fffff0', khaki: '#f0e68c', laserlemon: '#ffff54', lavender: '#e6e6fa', lavenderblush: '#fff0f5', lawngreen: '#7cfc00', lemonchiffon: '#fffacd', lightblue: '#add8e6', lightcoral: '#f08080', lightcyan: '#e0ffff', lightgoldenrod: '#fafad2', lightgoldenrodyellow: '#fafad2', lightgray: '#d3d3d3', lightgreen: '#90ee90', lightgrey: '#d3d3d3', lightpink: '#ffb6c1', lightsalmon: '#ffa07a', lightseagreen: '#20b2aa', lightskyblue: '#87cefa', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#b0c4de', lightyellow: '#ffffe0', lime: '#00ff00', limegreen: '#32cd32', linen: '#faf0e6', magenta: '#ff00ff', maroon: '#800000', maroon2: '#7f0000', maroon3: '#b03060', mediumaquamarine: '#66cdaa', mediumblue: '#0000cd', mediumorchid: '#ba55d3', mediumpurple: '#9370db', mediumseagreen: '#3cb371', mediumslateblue: '#7b68ee', mediumspringgreen: '#00fa9a', mediumturquoise: '#48d1cc', mediumvioletred: '#c71585', midnightblue: '#191970', mintcream: '#f5fffa', mistyrose: '#ffe4e1', moccasin: '#ffe4b5', navajowhite: '#ffdead', navy: '#000080', oldlace: '#fdf5e6', olive: '#808000', olivedrab: '#6b8e23', orange: '#ffa500', orangered: '#ff4500', orchid: '#da70d6', palegoldenrod: '#eee8aa', palegreen: '#98fb98', paleturquoise: '#afeeee', palevioletred: '#db7093', papayawhip: '#ffefd5', peachpuff: '#ffdab9', peru: '#cd853f', pink: '#ffc0cb', plum: '#dda0dd', powderblue: '#b0e0e6', purple: '#800080', purple2: '#7f007f', purple3: '#a020f0', rebeccapurple: '#663399', red: '#ff0000', rosybrown: '#bc8f8f', royalblue: '#4169e1', saddlebrown: '#8b4513', salmon: '#fa8072', sandybrown: '#f4a460', seagreen: '#2e8b57', seashell: '#fff5ee', sienna: '#a0522d', silver: '#c0c0c0', skyblue: '#87ceeb', slateblue: '#6a5acd', slategray: '#708090', slategrey: '#708090', snow: '#fffafa', springgreen: '#00ff7f', steelblue: '#4682b4', tan: '#d2b48c', teal: '#008080', thistle: '#d8bfd8', tomato: '#ff6347', turquoise: '#40e0d0', violet: '#ee82ee', wheat: '#f5deb3', white: '#ffffff', whitesmoke: '#f5f5f5', yellow: '#ffff00', yellowgreen: '#9acd32' }; var w3cx11_1 = w3cx11; var type$b = utils.type; Color_1.prototype.name = function() { var hex = rgb2hex_1(this._rgb, 'rgb'); for (var i = 0, list = Object.keys(w3cx11_1); i < list.length; i += 1) { var n = list[i]; if (w3cx11_1[n] === hex) { return n.toLowerCase(); } } return hex; }; input.format.named = function (name) { name = name.toLowerCase(); if (w3cx11_1[name]) { return hex2rgb_1(w3cx11_1[name]); } throw new Error('unknown color name: '+name); }; input.autodetect.push({ p: 5, test: function (h) { var rest = [], len = arguments.length - 1; while ( len-- > 0 ) rest[ len ] = arguments[ len + 1 ]; if (!rest.length && type$b(h) === 'string' && w3cx11_1[h.toLowerCase()]) { return 'named'; } } }); var unpack$t = utils.unpack; var rgb2num = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var ref = unpack$t(args, 'rgb'); var r = ref[0]; var g = ref[1]; var b = ref[2]; return (r << 16) + (g << 8) + b; }; var rgb2num_1 = rgb2num; var type$c = utils.type; var num2rgb = function (num) { if (type$c(num) == "number" && num >= 0 && num <= 0xFFFFFF) { var r = num >> 16; var g = (num >> 8) & 0xFF; var b = num & 0xFF; return [r,g,b,1]; } throw new Error("unknown num color: "+num); }; var num2rgb_1 = num2rgb; var type$d = utils.type; Color_1.prototype.num = function() { return rgb2num_1(this._rgb); }; chroma_1.num = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['num']) )); }; input.format.num = num2rgb_1; input.autodetect.push({ p: 5, test: function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; if (args.length === 1 && type$d(args[0]) === 'number' && args[0] >= 0 && args[0] <= 0xFFFFFF) { return 'num'; } } }); var unpack$u = utils.unpack; var type$e = utils.type; var round$5 = Math.round; Color_1.prototype.rgb = function(rnd) { if ( rnd === void 0 ) rnd=true; if (rnd === false) { return this._rgb.slice(0,3); } return this._rgb.slice(0,3).map(round$5); }; Color_1.prototype.rgba = function(rnd) { if ( rnd === void 0 ) rnd=true; return this._rgb.slice(0,4).map(function (v,i) { return i<3 ? (rnd === false ? v : round$5(v)) : v; }); }; chroma_1.rgb = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['rgb']) )); }; input.format.rgb = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var rgba = unpack$u(args, 'rgba'); if (rgba[3] === undefined) { rgba[3] = 1; } return rgba; }; input.autodetect.push({ p: 3, test: function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; args = unpack$u(args, 'rgba'); if (type$e(args) === 'array' && (args.length === 3 || args.length === 4 && type$e(args[3]) == 'number' && args[3] >= 0 && args[3] <= 1)) { return 'rgb'; } } }); /* * Based on implementation by Neil Bartlett * https://github.com/neilbartlett/color-temperature */ var log = Math.log; var temperature2rgb = function (kelvin) { var temp = kelvin / 100; var r,g,b; if (temp < 66) { r = 255; g = -155.25485562709179 - 0.44596950469579133 * (g = temp-2) + 104.49216199393888 * log(g); b = temp < 20 ? 0 : -254.76935184120902 + 0.8274096064007395 * (b = temp-10) + 115.67994401066147 * log(b); } else { r = 351.97690566805693 + 0.114206453784165 * (r = temp-55) - 40.25366309332127 * log(r); g = 325.4494125711974 + 0.07943456536662342 * (g = temp-50) - 28.0852963507957 * log(g); b = 255; } return [r,g,b,1]; }; var temperature2rgb_1 = temperature2rgb; /* * Based on implementation by Neil Bartlett * https://github.com/neilbartlett/color-temperature **/ var unpack$v = utils.unpack; var round$6 = Math.round; var rgb2temperature = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var rgb = unpack$v(args, 'rgb'); var r = rgb[0], b = rgb[2]; var minTemp = 1000; var maxTemp = 40000; var eps = 0.4; var temp; while (maxTemp - minTemp > eps) { temp = (maxTemp + minTemp) * 0.5; var rgb$1 = temperature2rgb_1(temp); if ((rgb$1[2] / rgb$1[0]) >= (b / r)) { maxTemp = temp; } else { minTemp = temp; } } return round$6(temp); }; var rgb2temperature_1 = rgb2temperature; Color_1.prototype.temp = Color_1.prototype.kelvin = Color_1.prototype.temperature = function() { return rgb2temperature_1(this._rgb); }; chroma_1.temp = chroma_1.kelvin = chroma_1.temperature = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['temp']) )); }; input.format.temp = input.format.kelvin = input.format.temperature = temperature2rgb_1; var type$f = utils.type; Color_1.prototype.alpha = function(a, mutate) { if ( mutate === void 0 ) mutate=false; if (a !== undefined && type$f(a) === 'number') { if (mutate) { this._rgb[3] = a; return this; } return new Color_1([this._rgb[0], this._rgb[1], this._rgb[2], a], 'rgb'); } return this._rgb[3]; }; Color_1.prototype.clipped = function() { return this._rgb._clipped || false; }; Color_1.prototype.darken = function(amount) { if ( amount === void 0 ) amount=1; var me = this; var lab = me.lab(); lab[0] -= labConstants.Kn * amount; return new Color_1(lab, 'lab').alpha(me.alpha(), true); }; Color_1.prototype.brighten = function(amount) { if ( amount === void 0 ) amount=1; return this.darken(-amount); }; Color_1.prototype.darker = Color_1.prototype.darken; Color_1.prototype.brighter = Color_1.prototype.brighten; Color_1.prototype.get = function(mc) { var ref = mc.split('.'); var mode = ref[0]; var channel = ref[1]; var src = this[mode](); if (channel) { var i = mode.indexOf(channel); if (i > -1) { return src[i]; } throw new Error(("unknown channel " + channel + " in mode " + mode)); } else { return src; } }; var type$g = utils.type; var pow$2 = Math.pow; var EPS = 1e-7; var MAX_ITER = 20; Color_1.prototype.luminance = function(lum) { if (lum !== undefined && type$g(lum) === 'number') { if (lum === 0) { // return pure black return new Color_1([0,0,0,this._rgb[3]], 'rgb'); } if (lum === 1) { // return pure white return new Color_1([255,255,255,this._rgb[3]], 'rgb'); } // compute new color using... var cur_lum = this.luminance(); var mode = 'rgb'; var max_iter = MAX_ITER; var test = function (low, high) { var mid = low.interpolate(high, 0.5, mode); var lm = mid.luminance(); if (Math.abs(lum - lm) < EPS || !max_iter--) { // close enough return mid; } return lm > lum ? test(low, mid) : test(mid, high); }; var rgb = (cur_lum > lum ? test(new Color_1([0,0,0]), this) : test(this, new Color_1([255,255,255]))).rgb(); return new Color_1(rgb.concat( [this._rgb[3]])); } return rgb2luminance.apply(void 0, (this._rgb).slice(0,3)); }; var rgb2luminance = function (r,g,b) { // relative luminance // see http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef r = luminance_x(r); g = luminance_x(g); b = luminance_x(b); return 0.2126 * r + 0.7152 * g + 0.0722 * b; }; var luminance_x = function (x) { x /= 255; return x <= 0.03928 ? x/12.92 : pow$2((x+0.055)/1.055, 2.4); }; var interpolator = {}; var type$h = utils.type; var mix = function (col1, col2, f) { if ( f === void 0 ) f=0.5; var rest = [], len = arguments.length - 3; while ( len-- > 0 ) rest[ len ] = arguments[ len + 3 ]; var mode = rest[0] || 'lrgb'; if (!interpolator[mode] && !rest.length) { // fall back to the first supported mode mode = Object.keys(interpolator)[0]; } if (!interpolator[mode]) { throw new Error(("interpolation mode " + mode + " is not defined")); } if (type$h(col1) !== 'object') { col1 = new Color_1(col1); } if (type$h(col2) !== 'object') { col2 = new Color_1(col2); } return interpolator[mode](col1, col2, f) .alpha(col1.alpha() + f * (col2.alpha() - col1.alpha())); }; Color_1.prototype.mix = Color_1.prototype.interpolate = function(col2, f) { if ( f === void 0 ) f=0.5; var rest = [], len = arguments.length - 2; while ( len-- > 0 ) rest[ len ] = arguments[ len + 2 ]; return mix.apply(void 0, [ this, col2, f ].concat( rest )); }; Color_1.prototype.premultiply = function(mutate) { if ( mutate === void 0 ) mutate=false; var rgb = this._rgb; var a = rgb[3]; if (mutate) { this._rgb = [rgb[0]*a, rgb[1]*a, rgb[2]*a, a]; return this; } else { return new Color_1([rgb[0]*a, rgb[1]*a, rgb[2]*a, a], 'rgb'); } }; Color_1.prototype.saturate = function(amount) { if ( amount === void 0 ) amount=1; var me = this; var lch = me.lch(); lch[1] += labConstants.Kn * amount; if (lch[1] < 0) { lch[1] = 0; } return new Color_1(lch, 'lch').alpha(me.alpha(), true); }; Color_1.prototype.desaturate = function(amount) { if ( amount === void 0 ) amount=1; return this.saturate(-amount); }; var type$i = utils.type; Color_1.prototype.set = function(mc, value, mutate) { if ( mutate === void 0 ) mutate=false; var ref = mc.split('.'); var mode = ref[0]; var channel = ref[1]; var src = this[mode](); if (channel) { var i = mode.indexOf(channel); if (i > -1) { if (type$i(value) == 'string') { switch(value.charAt(0)) { case '+': src[i] += +value; break; case '-': src[i] += +value; break; case '*': src[i] *= +(value.substr(1)); break; case '/': src[i] /= +(value.substr(1)); break; default: src[i] = +value; } } else if (type$i(value) === 'number') { src[i] = value; } else { throw new Error("unsupported value for Color.set"); } var out = new Color_1(src, mode); if (mutate) { this._rgb = out._rgb; return this; } return out; } throw new Error(("unknown channel " + channel + " in mode " + mode)); } else { return src; } }; var rgb$1 = function (col1, col2, f) { var xyz0 = col1._rgb; var xyz1 = col2._rgb; return new Color_1( xyz0[0] + f * (xyz1[0]-xyz0[0]), xyz0[1] + f * (xyz1[1]-xyz0[1]), xyz0[2] + f * (xyz1[2]-xyz0[2]), 'rgb' ) }; // register interpolator interpolator.rgb = rgb$1; var sqrt$2 = Math.sqrt; var pow$3 = Math.pow; var lrgb = function (col1, col2, f) { var ref = col1._rgb; var x1 = ref[0]; var y1 = ref[1]; var z1 = ref[2]; var ref$1 = col2._rgb; var x2 = ref$1[0]; var y2 = ref$1[1]; var z2 = ref$1[2]; return new Color_1( sqrt$2(pow$3(x1,2) * (1-f) + pow$3(x2,2) * f), sqrt$2(pow$3(y1,2) * (1-f) + pow$3(y2,2) * f), sqrt$2(pow$3(z1,2) * (1-f) + pow$3(z2,2) * f), 'rgb' ) }; // register interpolator interpolator.lrgb = lrgb; var lab$1 = function (col1, col2, f) { var xyz0 = col1.lab(); var xyz1 = col2.lab(); return new Color_1( xyz0[0] + f * (xyz1[0]-xyz0[0]), xyz0[1] + f * (xyz1[1]-xyz0[1]), xyz0[2] + f * (xyz1[2]-xyz0[2]), 'lab' ) }; // register interpolator interpolator.lab = lab$1; var _hsx = function (col1, col2, f, m) { var assign, assign$1; var xyz0, xyz1; if (m === 'hsl') { xyz0 = col1.hsl(); xyz1 = col2.hsl(); } else if (m === 'hsv') { xyz0 = col1.hsv(); xyz1 = col2.hsv(); } else if (m === 'hcg') { xyz0 = col1.hcg(); xyz1 = col2.hcg(); } else if (m === 'hsi') { xyz0 = col1.hsi(); xyz1 = col2.hsi(); } else if (m === 'lch' || m === 'hcl') { m = 'hcl'; xyz0 = col1.hcl(); xyz1 = col2.hcl(); } var hue0, hue1, sat0, sat1, lbv0, lbv1; if (m.substr(0, 1) === 'h') { (assign = xyz0, hue0 = assign[0], sat0 = assign[1], lbv0 = assign[2]); (assign$1 = xyz1, hue1 = assign$1[0], sat1 = assign$1[1], lbv1 = assign$1[2]); } var sat, hue, lbv, dh; if (!isNaN(hue0) && !isNaN(hue1)) { // both colors have hue if (hue1 > hue0 && hue1 - hue0 > 180) { dh = hue1-(hue0+360); } else if (hue1 < hue0 && hue0 - hue1 > 180) { dh = hue1+360-hue0; } else{ dh = hue1 - hue0; } hue = hue0 + f * dh; } else if (!isNaN(hue0)) { hue = hue0; if ((lbv1 == 1 || lbv1 == 0) && m != 'hsv') { sat = sat0; } } else if (!isNaN(hue1)) { hue = hue1; if ((lbv0 == 1 || lbv0 == 0) && m != 'hsv') { sat = sat1; } } else { hue = Number.NaN; } if (sat === undefined) { sat = sat0 + f * (sat1 - sat0); } lbv = lbv0 + f * (lbv1-lbv0); return new Color_1([hue, sat, lbv], m); }; var lch$1 = function (col1, col2, f) { return _hsx(col1, col2, f, 'lch'); }; // register interpolator interpolator.lch = lch$1; interpolator.hcl = lch$1; var num$1 = function (col1, col2, f) { var c1 = col1.num(); var c2 = col2.num(); return new Color_1(c1 + f * (c2-c1), 'num') }; // register interpolator interpolator.num = num$1; var hcg$1 = function (col1, col2, f) { return _hsx(col1, col2, f, 'hcg'); }; // register interpolator interpolator.hcg = hcg$1; var hsi$1 = function (col1, col2, f) { return _hsx(col1, col2, f, 'hsi'); }; // register interpolator interpolator.hsi = hsi$1; var hsl$1 = function (col1, col2, f) { return _hsx(col1, col2, f, 'hsl'); }; // register interpolator interpolator.hsl = hsl$1; var hsv$1 = function (col1, col2, f) { return _hsx(col1, col2, f, 'hsv'); }; // register interpolator interpolator.hsv = hsv$1; var clip_rgb$2 = utils.clip_rgb; var pow$4 = Math.pow; var sqrt$3 = Math.sqrt; var PI$1 = Math.PI; var cos$2 = Math.cos; var sin$1 = Math.sin; var atan2$1 = Math.atan2; var average = function (colors, mode, weights) { if ( mode === void 0 ) mode='lrgb'; if ( weights === void 0 ) weights=null; var l = colors.length; if (!weights) { weights = Array.from(new Array(l)).map(function () { return 1; }); } // normalize weights var k = l / weights.reduce(function(a, b) { return a + b; }); weights.forEach(function (w,i) { weights[i] *= k; }); // convert colors to Color objects colors = colors.map(function (c) { return new Color_1(c); }); if (mode === 'lrgb') { return _average_lrgb(colors, weights) } var first = colors.shift(); var xyz = first.get(mode); var cnt = []; var dx = 0; var dy = 0; // initial color for (var i=0; i= 360) { A$1 -= 360; } xyz[i$1] = A$1; } else { xyz[i$1] = xyz[i$1]/cnt[i$1]; } } alpha /= l; return (new Color_1(xyz, mode)).alpha(alpha > 0.99999 ? 1 : alpha, true); }; var _average_lrgb = function (colors, weights) { var l = colors.length; var xyz = [0,0,0,0]; for (var i=0; i < colors.length; i++) { var col = colors[i]; var f = weights[i] / l; var rgb = col._rgb; xyz[0] += pow$4(rgb[0],2) * f; xyz[1] += pow$4(rgb[1],2) * f; xyz[2] += pow$4(rgb[2],2) * f; xyz[3] += rgb[3] * f; } xyz[0] = sqrt$3(xyz[0]); xyz[1] = sqrt$3(xyz[1]); xyz[2] = sqrt$3(xyz[2]); if (xyz[3] > 0.9999999) { xyz[3] = 1; } return new Color_1(clip_rgb$2(xyz)); }; // minimal multi-purpose interface // @requires utils color analyze var type$j = utils.type; var pow$5 = Math.pow; var scale = function(colors) { // constructor var _mode = 'rgb'; var _nacol = chroma_1('#ccc'); var _spread = 0; // const _fixed = false; var _domain = [0, 1]; var _pos = []; var _padding = [0,0]; var _classes = false; var _colors = []; var _out = false; var _min = 0; var _max = 1; var _correctLightness = false; var _colorCache = {}; var _useCache = true; var _gamma = 1; // private methods var setColors = function(colors) { colors = colors || ['#fff', '#000']; if (colors && type$j(colors) === 'string' && chroma_1.brewer && chroma_1.brewer[colors.toLowerCase()]) { colors = chroma_1.brewer[colors.toLowerCase()]; } if (type$j(colors) === 'array') { // handle single color if (colors.length === 1) { colors = [colors[0], colors[0]]; } // make a copy of the colors colors = colors.slice(0); // convert to chroma classes for (var c=0; c= _classes[i]) { i++; } return i-1; } return 0; }; var tMapLightness = function (t) { return t; }; var tMapDomain = function (t) { return t; }; // const classifyValue = function(value) { // let val = value; // if (_classes.length > 2) { // const n = _classes.length-1; // const i = getClass(value); // const minc = _classes[0] + ((_classes[1]-_classes[0]) * (0 + (_spread * 0.5))); // center of 1st class // const maxc = _classes[n-1] + ((_classes[n]-_classes[n-1]) * (1 - (_spread * 0.5))); // center of last class // val = _min + ((((_classes[i] + ((_classes[i+1] - _classes[i]) * 0.5)) - minc) / (maxc-minc)) * (_max - _min)); // } // return val; // }; var getColor = function(val, bypassMap) { var col, t; if (bypassMap == null) { bypassMap = false; } if (isNaN(val) || (val === null)) { return _nacol; } if (!bypassMap) { if (_classes && (_classes.length > 2)) { // find the class var c = getClass(val); t = c / (_classes.length-2); } else if (_max !== _min) { // just interpolate between min/max t = (val - _min) / (_max - _min); } else { t = 1; } } else { t = val; } // domain map t = tMapDomain(t); if (!bypassMap) { t = tMapLightness(t); // lightness correction } if (_gamma !== 1) { t = pow$5(t, _gamma); } t = _padding[0] + (t * (1 - _padding[0] - _padding[1])); t = Math.min(1, Math.max(0, t)); var k = Math.floor(t * 10000); if (_useCache && _colorCache[k]) { col = _colorCache[k]; } else { if (type$j(_colors) === 'array') { //for i in [0.._pos.length-1] for (var i=0; i<_pos.length; i++) { var p = _pos[i]; if (t <= p) { col = _colors[i]; break; } if ((t >= p) && (i === (_pos.length-1))) { col = _colors[i]; break; } if (t > p && t < _pos[i+1]) { t = (t-p)/(_pos[i+1]-p); col = chroma_1.interpolate(_colors[i], _colors[i+1], t, _mode); break; } } } else if (type$j(_colors) === 'function') { col = _colors(t); } if (_useCache) { _colorCache[k] = col; } } return col; }; var resetCache = function () { return _colorCache = {}; }; setColors(colors); // public interface var f = function(v) { var c = chroma_1(getColor(v)); if (_out && c[_out]) { return c[_out](); } else { return c; } }; f.classes = function(classes) { if (classes != null) { if (type$j(classes) === 'array') { _classes = classes; _domain = [classes[0], classes[classes.length-1]]; } else { var d = chroma_1.analyze(_domain); if (classes === 0) { _classes = [d.min, d.max]; } else { _classes = chroma_1.limits(d, 'e', classes); } } return f; } return _classes; }; f.domain = function(domain) { if (!arguments.length) { return _domain; } _min = domain[0]; _max = domain[domain.length-1]; _pos = []; var k = _colors.length; if ((domain.length === k) && (_min !== _max)) { // update positions for (var i = 0, list = Array.from(domain); i < list.length; i += 1) { var d = list[i]; _pos.push((d-_min) / (_max-_min)); } } else { for (var c=0; c 2) { // set domain map var tOut = domain.map(function (d,i) { return i/(domain.length-1); }); var tBreaks = domain.map(function (d) { return (d - _min) / (_max - _min); }); if (!tBreaks.every(function (val, i) { return tOut[i] === val; })) { tMapDomain = function (t) { if (t <= 0 || t >= 1) { return t; } var i = 0; while (t >= tBreaks[i+1]) { i++; } var f = (t - tBreaks[i]) / (tBreaks[i+1] - tBreaks[i]); var out = tOut[i] + f * (tOut[i+1] - tOut[i]); return out; }; } } } _domain = [_min, _max]; return f; }; f.mode = function(_m) { if (!arguments.length) { return _mode; } _mode = _m; resetCache(); return f; }; f.range = function(colors, _pos) { setColors(colors, _pos); return f; }; f.out = function(_o) { _out = _o; return f; }; f.spread = function(val) { if (!arguments.length) { return _spread; } _spread = val; return f; }; f.correctLightness = function(v) { if (v == null) { v = true; } _correctLightness = v; resetCache(); if (_correctLightness) { tMapLightness = function(t) { var L0 = getColor(0, true).lab()[0]; var L1 = getColor(1, true).lab()[0]; var pol = L0 > L1; var L_actual = getColor(t, true).lab()[0]; var L_ideal = L0 + ((L1 - L0) * t); var L_diff = L_actual - L_ideal; var t0 = 0; var t1 = 1; var max_iter = 20; while ((Math.abs(L_diff) > 1e-2) && (max_iter-- > 0)) { (function() { if (pol) { L_diff *= -1; } if (L_diff < 0) { t0 = t; t += (t1 - t) * 0.5; } else { t1 = t; t += (t0 - t) * 0.5; } L_actual = getColor(t, true).lab()[0]; return L_diff = L_actual - L_ideal; })(); } return t; }; } else { tMapLightness = function (t) { return t; }; } return f; }; f.padding = function(p) { if (p != null) { if (type$j(p) === 'number') { p = [p,p]; } _padding = p; return f; } else { return _padding; } }; f.colors = function(numColors, out) { // If no arguments are given, return the original colors that were provided if (arguments.length < 2) { out = 'hex'; } var result = []; if (arguments.length === 0) { result = _colors.slice(0); } else if (numColors === 1) { result = [f(0.5)]; } else if (numColors > 1) { var dm = _domain[0]; var dd = _domain[1] - dm; result = __range__(0, numColors, false).map(function (i) { return f( dm + ((i/(numColors-1)) * dd) ); }); } else { // returns all colors based on the defined classes colors = []; var samples = []; if (_classes && (_classes.length > 2)) { for (var i = 1, end = _classes.length, asc = 1 <= end; asc ? i < end : i > end; asc ? i++ : i--) { samples.push((_classes[i-1]+_classes[i])*0.5); } } else { samples = _domain; } result = samples.map(function (v) { return f(v); }); } if (chroma_1[out]) { result = result.map(function (c) { return c[out](); }); } return result; }; f.cache = function(c) { if (c != null) { _useCache = c; return f; } else { return _useCache; } }; f.gamma = function(g) { if (g != null) { _gamma = g; return f; } else { return _gamma; } }; f.nodata = function(d) { if (d != null) { _nacol = chroma_1(d); return f; } else { return _nacol; } }; return f; }; function __range__(left, right, inclusive) { var range = []; var ascending = left < right; var end = !inclusive ? right : ascending ? right + 1 : right - 1; for (var i = left; ascending ? i < end : i > end; ascending ? i++ : i--) { range.push(i); } return range; } // // interpolates between a set of colors uzing a bezier spline // // @requires utils lab var bezier = function(colors) { var assign, assign$1, assign$2; var I, lab0, lab1, lab2; colors = colors.map(function (c) { return new Color_1(c); }); if (colors.length === 2) { // linear interpolation (assign = colors.map(function (c) { return c.lab(); }), lab0 = assign[0], lab1 = assign[1]); I = function(t) { var lab = ([0, 1, 2].map(function (i) { return lab0[i] + (t * (lab1[i] - lab0[i])); })); return new Color_1(lab, 'lab'); }; } else if (colors.length === 3) { // quadratic bezier interpolation (assign$1 = colors.map(function (c) { return c.lab(); }), lab0 = assign$1[0], lab1 = assign$1[1], lab2 = assign$1[2]); I = function(t) { var lab = ([0, 1, 2].map(function (i) { return ((1-t)*(1-t) * lab0[i]) + (2 * (1-t) * t * lab1[i]) + (t * t * lab2[i]); })); return new Color_1(lab, 'lab'); }; } else if (colors.length === 4) { // cubic bezier interpolation var lab3; (assign$2 = colors.map(function (c) { return c.lab(); }), lab0 = assign$2[0], lab1 = assign$2[1], lab2 = assign$2[2], lab3 = assign$2[3]); I = function(t) { var lab = ([0, 1, 2].map(function (i) { return ((1-t)*(1-t)*(1-t) * lab0[i]) + (3 * (1-t) * (1-t) * t * lab1[i]) + (3 * (1-t) * t * t * lab2[i]) + (t*t*t * lab3[i]); })); return new Color_1(lab, 'lab'); }; } else if (colors.length === 5) { var I0 = bezier(colors.slice(0, 3)); var I1 = bezier(colors.slice(2, 5)); I = function(t) { if (t < 0.5) { return I0(t*2); } else { return I1((t-0.5)*2); } }; } return I; }; var bezier_1 = function (colors) { var f = bezier(colors); f.scale = function () { return scale(f); }; return f; }; /* * interpolates between a set of colors uzing a bezier spline * blend mode formulas taken from http://www.venture-ware.com/kevin/coding/lets-learn-math-photoshop-blend-modes/ */ var blend = function (bottom, top, mode) { if (!blend[mode]) { throw new Error('unknown blend mode ' + mode); } return blend[mode](bottom, top); }; var blend_f = function (f) { return function (bottom,top) { var c0 = chroma_1(top).rgb(); var c1 = chroma_1(bottom).rgb(); return chroma_1.rgb(f(c0, c1)); }; }; var each = function (f) { return function (c0, c1) { var out = []; out[0] = f(c0[0], c1[0]); out[1] = f(c0[1], c1[1]); out[2] = f(c0[2], c1[2]); return out; }; }; var normal = function (a) { return a; }; var multiply = function (a,b) { return a * b / 255; }; var darken$1 = function (a,b) { return a > b ? b : a; }; var lighten = function (a,b) { return a > b ? a : b; }; var screen = function (a,b) { return 255 * (1 - (1-a/255) * (1-b/255)); }; var overlay = function (a,b) { return b < 128 ? 2 * a * b / 255 : 255 * (1 - 2 * (1 - a / 255 ) * ( 1 - b / 255 )); }; var burn = function (a,b) { return 255 * (1 - (1 - b / 255) / (a/255)); }; var dodge = function (a,b) { if (a === 255) { return 255; } a = 255 * (b / 255) / (1 - a / 255); return a > 255 ? 255 : a }; // # add = (a,b) -> // # if (a + b > 255) then 255 else a + b blend.normal = blend_f(each(normal)); blend.multiply = blend_f(each(multiply)); blend.screen = blend_f(each(screen)); blend.overlay = blend_f(each(overlay)); blend.darken = blend_f(each(darken$1)); blend.lighten = blend_f(each(lighten)); blend.dodge = blend_f(each(dodge)); blend.burn = blend_f(each(burn)); // blend.add = blend_f(each(add)); var blend_1 = blend; // cubehelix interpolation // based on D.A. Green "A colour scheme for the display of astronomical intensity images" // http://astron-soc.in/bulletin/11June/289392011.pdf var type$k = utils.type; var clip_rgb$3 = utils.clip_rgb; var TWOPI$2 = utils.TWOPI; var pow$6 = Math.pow; var sin$2 = Math.sin; var cos$3 = Math.cos; var cubehelix = function(start, rotations, hue, gamma, lightness) { if ( start === void 0 ) start=300; if ( rotations === void 0 ) rotations=-1.5; if ( hue === void 0 ) hue=1; if ( gamma === void 0 ) gamma=1; if ( lightness === void 0 ) lightness=[0,1]; var dh = 0, dl; if (type$k(lightness) === 'array') { dl = lightness[1] - lightness[0]; } else { dl = 0; lightness = [lightness, lightness]; } var f = function(fract) { var a = TWOPI$2 * (((start+120)/360) + (rotations * fract)); var l = pow$6(lightness[0] + (dl * fract), gamma); var h = dh !== 0 ? hue[0] + (fract * dh) : hue; var amp = (h * l * (1-l)) / 2; var cos_a = cos$3(a); var sin_a = sin$2(a); var r = l + (amp * ((-0.14861 * cos_a) + (1.78277* sin_a))); var g = l + (amp * ((-0.29227 * cos_a) - (0.90649* sin_a))); var b = l + (amp * (+1.97294 * cos_a)); return chroma_1(clip_rgb$3([r*255,g*255,b*255,1])); }; f.start = function(s) { if ((s == null)) { return start; } start = s; return f; }; f.rotations = function(r) { if ((r == null)) { return rotations; } rotations = r; return f; }; f.gamma = function(g) { if ((g == null)) { return gamma; } gamma = g; return f; }; f.hue = function(h) { if ((h == null)) { return hue; } hue = h; if (type$k(hue) === 'array') { dh = hue[1] - hue[0]; if (dh === 0) { hue = hue[1]; } } else { dh = 0; } return f; }; f.lightness = function(h) { if ((h == null)) { return lightness; } if (type$k(h) === 'array') { lightness = h; dl = h[1] - h[0]; } else { lightness = [h,h]; dl = 0; } return f; }; f.scale = function () { return chroma_1.scale(f); }; f.hue(hue); return f; }; var digits = '0123456789abcdef'; var floor$2 = Math.floor; var random = Math.random; var random_1 = function () { var code = '#'; for (var i=0; i<6; i++) { code += digits.charAt(floor$2(random() * 16)); } return new Color_1(code, 'hex'); }; var log$1 = Math.log; var pow$7 = Math.pow; var floor$3 = Math.floor; var abs = Math.abs; var analyze = function (data, key) { if ( key === void 0 ) key=null; var r = { min: Number.MAX_VALUE, max: Number.MAX_VALUE*-1, sum: 0, values: [], count: 0 }; if (type(data) === 'object') { data = Object.values(data); } data.forEach(function (val) { if (key && type(val) === 'object') { val = val[key]; } if (val !== undefined && val !== null && !isNaN(val)) { r.values.push(val); r.sum += val; if (val < r.min) { r.min = val; } if (val > r.max) { r.max = val; } r.count += 1; } }); r.domain = [r.min, r.max]; r.limits = function (mode, num) { return limits(r, mode, num); }; return r; }; var limits = function (data, mode, num) { if ( mode === void 0 ) mode='equal'; if ( num === void 0 ) num=7; if (type(data) == 'array') { data = analyze(data); } var min = data.min; var max = data.max; var values = data.values.sort(function (a,b) { return a-b; }); if (num === 1) { return [min,max]; } var limits = []; if (mode.substr(0,1) === 'c') { // continuous limits.push(min); limits.push(max); } if (mode.substr(0,1) === 'e') { // equal interval limits.push(min); for (var i=1; i 0'); } var min_log = Math.LOG10E * log$1(min); var max_log = Math.LOG10E * log$1(max); limits.push(min); for (var i$1=1; i$1 pb var pr = p - pb; limits.push((values[pb]*(1-pr)) + (values[pb+1]*pr)); } } limits.push(max); } else if (mode.substr(0,1) === 'k') { // k-means clustering /* implementation based on http://code.google.com/p/figue/source/browse/trunk/figue.js#336 simplified for 1-d input values */ var cluster; var n = values.length; var assignments = new Array(n); var clusterSizes = new Array(num); var repeat = true; var nb_iters = 0; var centroids = null; // get seed values centroids = []; centroids.push(min); for (var i$3=1; i$3 200) { repeat = false; } } // finished k-means clustering // the next part is borrowed from gabrielflor.it var kClusters = {}; for (var j$5=0; j$5 l2 ? (l1 + 0.05) / (l2 + 0.05) : (l2 + 0.05) / (l1 + 0.05); }; var sqrt$4 = Math.sqrt; var atan2$2 = Math.atan2; var abs$1 = Math.abs; var cos$4 = Math.cos; var PI$2 = Math.PI; var deltaE = function(a, b, L, C) { if ( L === void 0 ) L=1; if ( C === void 0 ) C=1; // Delta E (CMC) // see http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CMC.html a = new Color_1(a); b = new Color_1(b); var ref = Array.from(a.lab()); var L1 = ref[0]; var a1 = ref[1]; var b1 = ref[2]; var ref$1 = Array.from(b.lab()); var L2 = ref$1[0]; var a2 = ref$1[1]; var b2 = ref$1[2]; var c1 = sqrt$4((a1 * a1) + (b1 * b1)); var c2 = sqrt$4((a2 * a2) + (b2 * b2)); var sl = L1 < 16.0 ? 0.511 : (0.040975 * L1) / (1.0 + (0.01765 * L1)); var sc = ((0.0638 * c1) / (1.0 + (0.0131 * c1))) + 0.638; var h1 = c1 < 0.000001 ? 0.0 : (atan2$2(b1, a1) * 180.0) / PI$2; while (h1 < 0) { h1 += 360; } while (h1 >= 360) { h1 -= 360; } var t = (h1 >= 164.0) && (h1 <= 345.0) ? (0.56 + abs$1(0.2 * cos$4((PI$2 * (h1 + 168.0)) / 180.0))) : (0.36 + abs$1(0.4 * cos$4((PI$2 * (h1 + 35.0)) / 180.0))); var c4 = c1 * c1 * c1 * c1; var f = sqrt$4(c4 / (c4 + 1900.0)); var sh = sc * (((f * t) + 1.0) - f); var delL = L1 - L2; var delC = c1 - c2; var delA = a1 - a2; var delB = b1 - b2; var dH2 = ((delA * delA) + (delB * delB)) - (delC * delC); var v1 = delL / (L * sl); var v2 = delC / (C * sc); var v3 = sh; return sqrt$4((v1 * v1) + (v2 * v2) + (dH2 / (v3 * v3))); }; // simple Euclidean distance var distance = function(a, b, mode) { if ( mode === void 0 ) mode='lab'; // Delta E (CIE 1976) // see http://www.brucelindbloom.com/index.html?Equations.html a = new Color_1(a); b = new Color_1(b); var l1 = a.get(mode); var l2 = b.get(mode); var sum_sq = 0; for (var i in l1) { var d = (l1[i] || 0) - (l2[i] || 0); sum_sq += d*d; } return Math.sqrt(sum_sq); }; var valid = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; try { new (Function.prototype.bind.apply( Color_1, [ null ].concat( args) )); return true; } catch (e) { return false; } }; // some pre-defined color scales: var scales = { cool: function cool() { return scale([chroma_1.hsl(180,1,.9), chroma_1.hsl(250,.7,.4)]) }, hot: function hot() { return scale(['#000','#f00','#ff0','#fff'], [0,.25,.75,1]).mode('rgb') } }; /** ColorBrewer colors for chroma.js Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The Pennsylvania State University. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var colorbrewer = { // sequential OrRd: ['#fff7ec', '#fee8c8', '#fdd49e', '#fdbb84', '#fc8d59', '#ef6548', '#d7301f', '#b30000', '#7f0000'], PuBu: ['#fff7fb', '#ece7f2', '#d0d1e6', '#a6bddb', '#74a9cf', '#3690c0', '#0570b0', '#045a8d', '#023858'], BuPu: ['#f7fcfd', '#e0ecf4', '#bfd3e6', '#9ebcda', '#8c96c6', '#8c6bb1', '#88419d', '#810f7c', '#4d004b'], Oranges: ['#fff5eb', '#fee6ce', '#fdd0a2', '#fdae6b', '#fd8d3c', '#f16913', '#d94801', '#a63603', '#7f2704'], BuGn: ['#f7fcfd', '#e5f5f9', '#ccece6', '#99d8c9', '#66c2a4', '#41ae76', '#238b45', '#006d2c', '#00441b'], YlOrBr: ['#ffffe5', '#fff7bc', '#fee391', '#fec44f', '#fe9929', '#ec7014', '#cc4c02', '#993404', '#662506'], YlGn: ['#ffffe5', '#f7fcb9', '#d9f0a3', '#addd8e', '#78c679', '#41ab5d', '#238443', '#006837', '#004529'], Reds: ['#fff5f0', '#fee0d2', '#fcbba1', '#fc9272', '#fb6a4a', '#ef3b2c', '#cb181d', '#a50f15', '#67000d'], RdPu: ['#fff7f3', '#fde0dd', '#fcc5c0', '#fa9fb5', '#f768a1', '#dd3497', '#ae017e', '#7a0177', '#49006a'], Greens: ['#f7fcf5', '#e5f5e0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#006d2c', '#00441b'], YlGnBu: ['#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#253494', '#081d58'], Purples: ['#fcfbfd', '#efedf5', '#dadaeb', '#bcbddc', '#9e9ac8', '#807dba', '#6a51a3', '#54278f', '#3f007d'], GnBu: ['#f7fcf0', '#e0f3db', '#ccebc5', '#a8ddb5', '#7bccc4', '#4eb3d3', '#2b8cbe', '#0868ac', '#084081'], Greys: ['#ffffff', '#f0f0f0', '#d9d9d9', '#bdbdbd', '#969696', '#737373', '#525252', '#252525', '#000000'], YlOrRd: ['#ffffcc', '#ffeda0', '#fed976', '#feb24c', '#fd8d3c', '#fc4e2a', '#e31a1c', '#bd0026', '#800026'], PuRd: ['#f7f4f9', '#e7e1ef', '#d4b9da', '#c994c7', '#df65b0', '#e7298a', '#ce1256', '#980043', '#67001f'], Blues: ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b'], PuBuGn: ['#fff7fb', '#ece2f0', '#d0d1e6', '#a6bddb', '#67a9cf', '#3690c0', '#02818a', '#016c59', '#014636'], Viridis: ['#440154', '#482777', '#3f4a8a', '#31678e', '#26838f', '#1f9d8a', '#6cce5a', '#b6de2b', '#fee825'], // diverging Spectral: ['#9e0142', '#d53e4f', '#f46d43', '#fdae61', '#fee08b', '#ffffbf', '#e6f598', '#abdda4', '#66c2a5', '#3288bd', '#5e4fa2'], RdYlGn: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee08b', '#ffffbf', '#d9ef8b', '#a6d96a', '#66bd63', '#1a9850', '#006837'], RdBu: ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#f7f7f7', '#d1e5f0', '#92c5de', '#4393c3', '#2166ac', '#053061'], PiYG: ['#8e0152', '#c51b7d', '#de77ae', '#f1b6da', '#fde0ef', '#f7f7f7', '#e6f5d0', '#b8e186', '#7fbc41', '#4d9221', '#276419'], PRGn: ['#40004b', '#762a83', '#9970ab', '#c2a5cf', '#e7d4e8', '#f7f7f7', '#d9f0d3', '#a6dba0', '#5aae61', '#1b7837', '#00441b'], RdYlBu: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#ffffbf', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695'], BrBG: ['#543005', '#8c510a', '#bf812d', '#dfc27d', '#f6e8c3', '#f5f5f5', '#c7eae5', '#80cdc1', '#35978f', '#01665e', '#003c30'], RdGy: ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#ffffff', '#e0e0e0', '#bababa', '#878787', '#4d4d4d', '#1a1a1a'], PuOr: ['#7f3b08', '#b35806', '#e08214', '#fdb863', '#fee0b6', '#f7f7f7', '#d8daeb', '#b2abd2', '#8073ac', '#542788', '#2d004b'], // qualitative Set2: ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854', '#ffd92f', '#e5c494', '#b3b3b3'], Accent: ['#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f', '#bf5b17', '#666666'], Set1: ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628', '#f781bf', '#999999'], Set3: ['#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5', '#ffed6f'], Dark2: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d', '#666666'], Paired: ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a', '#ffff99', '#b15928'], Pastel2: ['#b3e2cd', '#fdcdac', '#cbd5e8', '#f4cae4', '#e6f5c9', '#fff2ae', '#f1e2cc', '#cccccc'], Pastel1: ['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4', '#fed9a6', '#ffffcc', '#e5d8bd', '#fddaec', '#f2f2f2'], }; // add lowercase aliases for case-insensitive matches for (var i$1 = 0, list$1 = Object.keys(colorbrewer); i$1 < list$1.length; i$1 += 1) { var key = list$1[i$1]; colorbrewer[key.toLowerCase()] = colorbrewer[key]; } var colorbrewer_1 = colorbrewer; // feel free to comment out anything to rollup // a smaller chroma.js built // io --> convert colors // operators --> modify existing Colors // interpolators // generators -- > create new colors chroma_1.average = average; chroma_1.bezier = bezier_1; chroma_1.blend = blend_1; chroma_1.cubehelix = cubehelix; chroma_1.mix = chroma_1.interpolate = mix; chroma_1.random = random_1; chroma_1.scale = scale; // other utility methods chroma_1.analyze = analyze_1.analyze; chroma_1.contrast = contrast; chroma_1.deltaE = deltaE; chroma_1.distance = distance; chroma_1.limits = analyze_1.limits; chroma_1.valid = valid; // scale chroma_1.scales = scales; // colors chroma_1.colors = w3cx11_1; chroma_1.brewer = colorbrewer_1; var chroma_js = chroma_1; return chroma_js; }))); },{}],46:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var ColorScheme, slice = [].slice; ColorScheme = (function() { var clone, l, len, ref, typeIsArray, word; typeIsArray = Array.isArray || function(value) { return {}.toString.call(value) === '[object Array]'; }; ColorScheme.SCHEMES = {}; ref = "mono monochromatic contrast triade tetrade analogic".split(/\s+/); for (l = 0, len = ref.length; l < len; l++) { word = ref[l]; ColorScheme.SCHEMES[word] = true; } ColorScheme.PRESETS = { "default": [-1, -1, 1, -0.7, 0.25, 1, 0.5, 1], pastel: [0.5, -0.9, 0.5, 0.5, 0.1, 0.9, 0.75, 0.75], soft: [0.3, -0.8, 0.3, 0.5, 0.1, 0.9, 0.5, 0.75], light: [0.25, 1, 0.5, 0.75, 0.1, 1, 0.5, 1], hard: [1, -1, 1, -0.6, 0.1, 1, 0.6, 1], pale: [0.1, -0.85, 0.1, 0.5, 0.1, 1, 0.1, 0.75] }; ColorScheme.COLOR_WHEEL = { 0: [255, 0, 0, 100], 15: [255, 51, 0, 100], 30: [255, 102, 0, 100], 45: [255, 128, 0, 100], 60: [255, 153, 0, 100], 75: [255, 178, 0, 100], 90: [255, 204, 0, 100], 105: [255, 229, 0, 100], 120: [255, 255, 0, 100], 135: [204, 255, 0, 100], 150: [153, 255, 0, 100], 165: [51, 255, 0, 100], 180: [0, 204, 0, 80], 195: [0, 178, 102, 70], 210: [0, 153, 153, 60], 225: [0, 102, 178, 70], 240: [0, 51, 204, 80], 255: [25, 25, 178, 70], 270: [51, 0, 153, 60], 285: [64, 0, 153, 60], 300: [102, 0, 153, 60], 315: [153, 0, 153, 60], 330: [204, 0, 153, 80], 345: [229, 0, 102, 90] }; function ColorScheme() { var colors, m; colors = []; for (m = 1; m <= 4; m++) { colors.push(new ColorScheme.mutablecolor(60)); } this.col = colors; this._scheme = 'mono'; this._distance = 0.5; this._web_safe = false; this._add_complement = false; } /* colors() Returns an array of 4, 8, 12 or 16 colors in RRGGBB hexidecimal notation (without a leading "#") depending on the color scheme and addComplement parameter. For each set of four, the first is usually the most saturated color, the second a darkened version, the third a pale version and fourth a less-pale version. For example: With a contrast scheme, "colors()" would return eight colors. Indexes 1 and 5 could be background colors, 2 and 6 could be foreground colors. Trust me, it's much better if you check out the Color Scheme web site, whose URL is listed in "Description" */ ColorScheme.prototype.colors = function() { var dispatch, h, i, j, m, n, output, ref1, used_colors; used_colors = 1; h = this.col[0].get_hue(); dispatch = { mono: (function(_this) { return function() {}; })(this), contrast: (function(_this) { return function() { used_colors = 2; _this.col[1].set_hue(h); return _this.col[1].rotate(180); }; })(this), triade: (function(_this) { return function() { var dif; used_colors = 3; dif = 60 * _this._distance; _this.col[1].set_hue(h); _this.col[1].rotate(180 - dif); _this.col[2].set_hue(h); return _this.col[2].rotate(180 + dif); }; })(this), tetrade: (function(_this) { return function() { var dif; used_colors = 4; dif = 90 * _this._distance; _this.col[1].set_hue(h); _this.col[1].rotate(180); _this.col[2].set_hue(h); _this.col[2].rotate(180 + dif); _this.col[3].set_hue(h); return _this.col[3].rotate(dif); }; })(this), analogic: (function(_this) { return function() { var dif; used_colors = _this._add_complement ? 4 : 3; dif = 60 * _this._distance; _this.col[1].set_hue(h); _this.col[1].rotate(dif); _this.col[2].set_hue(h); _this.col[2].rotate(360 - dif); _this.col[3].set_hue(h); return _this.col[3].rotate(180); }; })(this) }; dispatch['monochromatic'] = dispatch['mono']; if (dispatch[this._scheme] != null) { dispatch[this._scheme](); } else { throw "Unknown color scheme name: " + this._scheme; } output = []; for (i = m = 0, ref1 = used_colors - 1; 0 <= ref1 ? m <= ref1 : m >= ref1; i = 0 <= ref1 ? ++m : --m) { for (j = n = 0; n <= 3; j = ++n) { output[i * 4 + j] = this.col[i].get_hex(this._web_safe, j); } } return output; }; /* colorset() Returns a list of lists of the colors in groups of four. This method simply allows you to reference a color in the scheme by its group isntead of its absolute index in the list of colors. I am assuming that "colorset()" will make it easier to use this module with the templating systems that are out there. For example, if you were to follow the synopsis, say you wanted to retrieve the two darkest colors from the first two groups of the scheme, which is typically the second color in the group. You could retrieve them with "colors()" first_background = (scheme.colors())[1]; second_background = (scheme.colors())[5]; Or, with this method, first_background = (scheme.colorset())[0][1] second_background = (scheme.colorset())[1][1] */ ColorScheme.prototype.colorset = function() { var flat_colors, grouped_colors; flat_colors = clone(this.colors()); grouped_colors = []; while (flat_colors.length > 0) { grouped_colors.push(flat_colors.splice(0, 4)); } return grouped_colors; }; /* from_hue( degrees ) Sets the base color hue, where 'degrees' is an integer. (Values greater than 359 and less than 0 wrap back around the wheel.) The default base hue is 0, or bright red. */ ColorScheme.prototype.from_hue = function(h) { if (h == null) { throw "from_hue needs an argument"; } this.col[0].set_hue(h); return this; }; ColorScheme.prototype.rgb2ryb = function() { var blue, green, iN, maxgreen, maxyellow, red, rgb, white, yellow; rgb = 1 <= arguments.length ? slice.call(arguments, 0) : []; if ((rgb[0] != null) && typeIsArray(rgb[0])) { rgb = rgb[0]; } red = rgb[0], green = rgb[1], blue = rgb[2]; white = Math.min(red, green, blue); red -= white; green -= white; blue -= white; maxgreen = Math.max(red, green, blue); yellow = Math.min(red, green); red -= yellow; green -= yellow; if (blue > 0 && green > 0) { blue /= 2; green /= 2; } yellow += green; blue += green; maxyellow = Math.max(red, yellow, blue); if (maxyellow > 0) { iN = maxgreen / maxyellow; red *= iN; yellow *= iN; blue *= iN; } red += white; yellow += white; blue += white; return [Math.floor(red), Math.floor(yellow), Math.floor(blue)]; }; ColorScheme.prototype.rgb2hsv = function() { var b, d, g, h, max, min, r, rgb, s, v; rgb = 1 <= arguments.length ? slice.call(arguments, 0) : []; if ((rgb[0] != null) && typeIsArray(rgb[0])) { rgb = rgb[0]; } r = rgb[0], g = rgb[1], b = rgb[2]; r /= 255; g /= 255; b /= 255; min = Math.min.apply(Math, [r, g, b]); max = Math.max.apply(Math, [r, g, b]); d = max - min; v = max; s; if (d > 0) { s = d / max; } else { return [0, 0, v]; } h = (r === max ? (g - b) / d : (g === max ? 2 + (b - r) / d : 4 + (r - g) / d)); h *= 60; h %= 360; return [h, s, v]; }; ColorScheme.prototype.rgbToHsv = function() { var b, d, g, h, max, min, r, rgb, s, v; rgb = 1 <= arguments.length ? slice.call(arguments, 0) : []; if ((rgb[0] != null) && typeIsArray(rgb[0])) { rgb = rgb[0]; } r = rgb[0], g = rgb[1], b = rgb[2]; r /= 255; g /= 255; b /= 255; max = Math.max(r, g, b); min = Math.min(r, g, b); h = void 0; s = void 0; v = max; d = max - min; s = max === 0 ? 0 : d / max; if (max === min) { h = 0; } else { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; } h /= 6; } return [h, s, v]; }; /* from_hex( color ) Sets the base color to the given color, where 'color' is in the hexidecimal form RRGGBB. 'color' should not be preceded with a hash (#). The default base color is the equivalent of #ff0000, or bright red. */ ColorScheme.prototype.from_hex = function(hex) { var b, g, h, h0, h1, h2, hsv, i1, i2, num, r, ref1, ref2, rgbcap, s, v; if (hex == null) { throw "from_hex needs an argument"; } if (!/^([0-9A-F]{2}){3}$/im.test(hex)) { throw "from_hex(" + hex + ") - argument must be in the form of RRGGBB"; } rgbcap = /(..)(..)(..)/.exec(hex).slice(1, 4); ref1 = (function() { var len1, m, results; results = []; for (m = 0, len1 = rgbcap.length; m < len1; m++) { num = rgbcap[m]; results.push(parseInt(num, 16)); } return results; })(), r = ref1[0], g = ref1[1], b = ref1[2]; ref2 = this.rgb2ryb([r, g, b]), r = ref2[0], g = ref2[1], b = ref2[2]; hsv = this.rgbToHsv(r, g, b); h0 = hsv[0]; h1 = 0; h2 = 1000; i1 = null; i2 = null; h = null; s = null; v = null; h = hsv[0]; s = hsv[1]; v = hsv[2]; this.from_hue(h * 360); this._set_variant_preset([s, v, s, v * 0.7, s * 0.25, 1, s * 0.5, 1]); return this; }; /* add_complement( BOOLEAN ) If BOOLEAN is true, an extra set of colors will be produced using the complement of the selected color. This only works with the analogic color scheme. The default is false. */ ColorScheme.prototype.add_complement = function(b) { if (b == null) { throw "add_complement needs an argument"; } this._add_complement = b; return this; }; /* web_safe( BOOL ) Sets whether the colors returned by L<"colors()"> or L<"colorset()"> will be web-safe. The default is false. */ ColorScheme.prototype.web_safe = function(b) { if (b == null) { throw "web_safe needs an argument"; } this._web_safe = b; return this; }; /* distance( FLOAT ) 'FLOAT'> must be a value from 0 to 1. You might use this with the "triade" "tetrade" or "analogic" color schemes. The default is 0.5. */ ColorScheme.prototype.distance = function(d) { if (d == null) { throw "distance needs an argument"; } if (d < 0) { throw "distance(" + d + ") - argument must be >= 0"; } if (d > 1) { throw "distance(" + d + ") - argument must be <= 1"; } this._distance = d; return this; }; /* scheme( name ) 'name' must be a valid color scheme name. See "Color Schemes". The default is "mono" */ ColorScheme.prototype.scheme = function(name) { if (name == null) { return this._scheme; } else { if (ColorScheme.SCHEMES[name] == null) { throw "'" + name + "' isn't a valid scheme name"; } this._scheme = name; return this; } }; /* variation( name ) 'name' must be a valid color variation name. See "Color Variations" */ ColorScheme.prototype.variation = function(v) { if (v == null) { throw "variation needs an argument"; } if (ColorScheme.PRESETS[v] == null) { throw "'$v' isn't a valid variation name"; } this._set_variant_preset(ColorScheme.PRESETS[v]); return this; }; ColorScheme.prototype._set_variant_preset = function(p) { var i, m, results; results = []; for (i = m = 0; m <= 3; i = ++m) { results.push(this.col[i].set_variant_preset(p)); } return results; }; clone = function(obj) { var flags, key, newInstance; if ((obj == null) || typeof obj !== 'object') { return obj; } if (obj instanceof Date) { return new Date(obj.getTime()); } if (obj instanceof RegExp) { flags = ''; if (obj.global != null) { flags += 'g'; } if (obj.ignoreCase != null) { flags += 'i'; } if (obj.multiline != null) { flags += 'm'; } if (obj.sticky != null) { flags += 'y'; } return new RegExp(obj.source, flags); } newInstance = new obj.constructor(); for (key in obj) { newInstance[key] = clone(obj[key]); } return newInstance; }; ColorScheme.mutablecolor = (function() { mutablecolor.prototype.hue = 0; mutablecolor.prototype.saturation = []; mutablecolor.prototype.value = []; mutablecolor.prototype.base_red = 0; mutablecolor.prototype.base_green = 0; mutablecolor.prototype.base_saturation = 0; mutablecolor.prototype.base_value = 0; function mutablecolor(hue) { if (hue == null) { throw "No hue specified"; } this.saturation = []; this.value = []; this.base_red = 0; this.base_green = 0; this.base_blue = 0; this.base_saturation = 0; this.base_value = 0; this.set_hue(hue); this.set_variant_preset(ColorScheme.PRESETS['default']); } mutablecolor.prototype.get_hue = function() { return this.hue; }; mutablecolor.prototype.set_hue = function(h) { var avrg, color, colorset1, colorset2, d, derivative1, derivative2, en, i, k; avrg = function(a, b, k) { return a + Math.round((b - a) * k); }; this.hue = Math.round(h % 360); d = this.hue % 15 + (this.hue - Math.floor(this.hue)); k = d / 15; derivative1 = this.hue - Math.floor(d); derivative2 = (derivative1 + 15) % 360; if (derivative1 === 360) { derivative1 = 0; } if (derivative2 === 360) { derivative2 = 0; } colorset1 = ColorScheme.COLOR_WHEEL[derivative1]; colorset2 = ColorScheme.COLOR_WHEEL[derivative2]; en = { red: 0, green: 1, blue: 2, value: 3 }; for (color in en) { i = en[color]; this["base_" + color] = avrg(colorset1[i], colorset2[i], k); } this.base_saturation = avrg(100, 100, k) / 100; return this.base_value /= 100; }; mutablecolor.prototype.rotate = function(angle) { var newhue; newhue = (this.hue + angle) % 360; return this.set_hue(newhue); }; mutablecolor.prototype.get_saturation = function(variation) { var s, x; x = this.saturation[variation]; s = x < 0 ? -x * this.base_saturation : x; if (s > 1) { s = 1; } if (s < 0) { s = 0; } return s; }; mutablecolor.prototype.get_value = function(variation) { var v, x; x = this.value[variation]; v = x < 0 ? -x * this.base_value : x; if (v > 1) { v = 1; } if (v < 0) { v = 0; } return v; }; mutablecolor.prototype.set_variant = function(variation, s, v) { this.saturation[variation] = s; return this.value[variation] = v; }; mutablecolor.prototype.set_variant_preset = function(p) { var i, m, results; results = []; for (i = m = 0; m <= 3; i = ++m) { results.push(this.set_variant(i, p[2 * i], p[2 * i + 1])); } return results; }; mutablecolor.prototype.get_hex = function(web_safe, variation) { var c, color, formatted, i, k, len1, len2, m, max, min, n, ref1, rgb, rgbVal, s, str, v; max = Math.max.apply(Math, (function() { var len1, m, ref1, results; ref1 = ['red', 'green', 'blue']; results = []; for (m = 0, len1 = ref1.length; m < len1; m++) { color = ref1[m]; results.push(this["base_" + color]); } return results; }).call(this)); min = Math.min.apply(Math, (function() { var len1, m, ref1, results; ref1 = ['red', 'green', 'blue']; results = []; for (m = 0, len1 = ref1.length; m < len1; m++) { color = ref1[m]; results.push(this["base_" + color]); } return results; }).call(this)); v = (variation < 0 ? this.base_value : this.get_value(variation)) * 255; s = variation < 0 ? this.base_saturation : this.get_saturation(variation); k = max > 0 ? v / max : 0; rgb = []; ref1 = ['red', 'green', 'blue']; for (m = 0, len1 = ref1.length; m < len1; m++) { color = ref1[m]; rgbVal = Math.min.apply(Math, [255, Math.round(v - (v - this["base_" + color] * k) * s)]); rgb.push(rgbVal); } if (web_safe) { rgb = (function() { var len2, n, results; results = []; for (n = 0, len2 = rgb.length; n < len2; n++) { c = rgb[n]; results.push(Math.round(c / 51) * 51); } return results; })(); } formatted = ""; for (n = 0, len2 = rgb.length; n < len2; n++) { i = rgb[n]; str = i.toString(16); if (str.length < 2) { str = "0" + str; } formatted += str; } return formatted; }; return mutablecolor; })(); return ColorScheme; })(); if ((typeof module !== "undefined" && module !== null) && (module.exports != null)) { module.exports = ColorScheme; } else { if (typeof define === 'function' && define.amd) { define([], function() { return ColorScheme; }); } else { window.ColorScheme = ColorScheme; } } }).call(this); },{}],47:[function(require,module,exports){ /** * Expose `Emitter`. */ if (typeof module !== 'undefined') { module.exports = Emitter; } /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } // Remove event specific arrays for event types that no // one is subscribed for to avoid memory leak. if (callbacks.length === 0) { delete this._callbacks['$' + event]; } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = new Array(arguments.length - 1) , callbacks = this._callbacks['$' + event]; for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],48:[function(require,module,exports){ (function (process){ function detect() { if (typeof navigator !== 'undefined') { return parseUserAgent(navigator.userAgent); } return getNodeVersion(); } function detectOS(userAgentString) { var rules = getOperatingSystemRules(); var detected = rules.filter(function (os) { return os.rule && os.rule.test(userAgentString); })[0]; return detected ? detected.name : null; } function getNodeVersion() { var isNode = typeof process !== 'undefined' && process.version; return isNode && { name: 'node', version: process.version.slice(1), os: process.platform }; } function parseUserAgent(userAgentString) { var browsers = getBrowserRules(); if (!userAgentString) { return null; } var detected = browsers.map(function(browser) { var match = browser.rule.exec(userAgentString); var version = match && match[1].split(/[._]/).slice(0,3); if (version && version.length < 3) { version = version.concat(version.length == 1 ? [0, 0] : [0]); } return match && { name: browser.name, version: version.join('.') }; }).filter(Boolean)[0] || null; if (detected) { detected.os = detectOS(userAgentString); } if (/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/i.test(userAgentString)) { detected = detected || {}; detected.bot = true; } return detected; } function getBrowserRules() { return buildRules([ [ 'aol', /AOLShield\/([0-9\._]+)/ ], [ 'edge', /Edge\/([0-9\._]+)/ ], [ 'yandexbrowser', /YaBrowser\/([0-9\._]+)/ ], [ 'vivaldi', /Vivaldi\/([0-9\.]+)/ ], [ 'kakaotalk', /KAKAOTALK\s([0-9\.]+)/ ], [ 'samsung', /SamsungBrowser\/([0-9\.]+)/ ], [ 'chrome', /(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/ ], [ 'phantomjs', /PhantomJS\/([0-9\.]+)(:?\s|$)/ ], [ 'crios', /CriOS\/([0-9\.]+)(:?\s|$)/ ], [ 'firefox', /Firefox\/([0-9\.]+)(?:\s|$)/ ], [ 'fxios', /FxiOS\/([0-9\.]+)/ ], [ 'opera', /Opera\/([0-9\.]+)(?:\s|$)/ ], [ 'opera', /OPR\/([0-9\.]+)(:?\s|$)$/ ], [ 'ie', /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/ ], [ 'ie', /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/ ], [ 'ie', /MSIE\s(7\.0)/ ], [ 'bb10', /BB10;\sTouch.*Version\/([0-9\.]+)/ ], [ 'android', /Android\s([0-9\.]+)/ ], [ 'ios', /Version\/([0-9\._]+).*Mobile.*Safari.*/ ], [ 'safari', /Version\/([0-9\._]+).*Safari/ ], [ 'facebook', /FBAV\/([0-9\.]+)/], [ 'instagram', /Instagram\s([0-9\.]+)/], [ 'ios-webview', /AppleWebKit\/([0-9\.]+).*Mobile/] ]); } function getOperatingSystemRules() { return buildRules([ [ 'iOS', /iP(hone|od|ad)/ ], [ 'Android OS', /Android/ ], [ 'BlackBerry OS', /BlackBerry|BB10/ ], [ 'Windows Mobile', /IEMobile/ ], [ 'Amazon OS', /Kindle/ ], [ 'Windows 3.11', /Win16/ ], [ 'Windows 95', /(Windows 95)|(Win95)|(Windows_95)/ ], [ 'Windows 98', /(Windows 98)|(Win98)/ ], [ 'Windows 2000', /(Windows NT 5.0)|(Windows 2000)/ ], [ 'Windows XP', /(Windows NT 5.1)|(Windows XP)/ ], [ 'Windows Server 2003', /(Windows NT 5.2)/ ], [ 'Windows Vista', /(Windows NT 6.0)/ ], [ 'Windows 7', /(Windows NT 6.1)/ ], [ 'Windows 8', /(Windows NT 6.2)/ ], [ 'Windows 8.1', /(Windows NT 6.3)/ ], [ 'Windows 10', /(Windows NT 10.0)/ ], [ 'Windows ME', /Windows ME/ ], [ 'Open BSD', /OpenBSD/ ], [ 'Sun OS', /SunOS/ ], [ 'Linux', /(Linux)|(X11)/ ], [ 'Mac OS', /(Mac_PowerPC)|(Macintosh)/ ], [ 'QNX', /QNX/ ], [ 'BeOS', /BeOS/ ], [ 'OS/2', /OS\/2/ ], [ 'Search Bot', /(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves\/Teoma)|(ia_archiver)/ ] ]); } function buildRules(ruleTuples) { return ruleTuples.map(function(tuple) { return { name: tuple[0], rule: tuple[1] }; }); } module.exports = { detect: detect, detectOS: detectOS, getNodeVersion: getNodeVersion, parseUserAgent: parseUserAgent }; }).call(this,require('_process')) },{"_process":379}],49:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _utils = _interopRequireDefault(require("./utils")); var _deepClone = _interopRequireDefault(require("mout/lang/deepClone")); var _deepEquals = _interopRequireDefault(require("mout/lang/deepEquals")); var _chromaJs = _interopRequireDefault(require("chroma-js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _createForOfIteratorHelper(o) { if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) { var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var it, normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var defaults = { count: 5, hueMin: 0, hueMax: 360, chromaMin: 0, chromaMax: 100, lightMin: 0, lightMax: 100, quality: 50, samples: 800 }; var getClosestIndex = function getClosestIndex(colors, color) { var minDist = Number.MAX_SAFE_INTEGER; var nearest = 0; for (var idx = 0; idx < colors.length; idx += 1) { var sample = colors[idx]; var dist = Math.sqrt(Math.pow(Math.abs(sample[0] - color[0]), 2) + Math.pow(Math.abs(sample[1] - color[1]), 2) + Math.pow(Math.abs(sample[2] - color[2]), 2)); if (dist < minDist) { minDist = dist; nearest = idx; } } return nearest; }; var checkColor = function checkColor(lab, options) { var color = _chromaJs["default"].lab(lab); var hcl = color.hcl(); var rgb = color.rgb(); var compLab = _chromaJs["default"].rgb(rgb).lab(); var labTolerance = 2; return hcl[0] >= options.hueMin && hcl[0] <= options.hueMax && hcl[1] >= options.chromaMin && hcl[1] <= options.chromaMax && hcl[2] >= options.lightMin && hcl[2] <= options.lightMax && compLab[0] >= lab[0] - labTolerance && compLab[0] <= lab[0] + labTolerance && compLab[1] >= lab[1] - labTolerance && compLab[1] <= lab[1] + labTolerance && compLab[2] >= lab[2] - labTolerance && compLab[2] <= lab[2] + labTolerance; }; var sortByContrast = function sortByContrast(colorList) { var unsortedColors = colorList.slice(0); var sortedColors = [unsortedColors.shift()]; while (unsortedColors.length > 0) { var lastColor = sortedColors[sortedColors.length - 1]; var nearest = 0; var maxDist = Number.MIN_SAFE_INTEGER; for (var i = 0; i < unsortedColors.length; i += 1) { var dist = Math.sqrt(Math.pow(Math.abs(lastColor[0] - unsortedColors[i][0]), 2) + Math.pow(Math.abs(lastColor[1] - unsortedColors[i][1]), 2) + Math.pow(Math.abs(lastColor[2] - unsortedColors[i][2]), 2)); if (dist > maxDist) { maxDist = dist; nearest = i; } } sortedColors.push(unsortedColors.splice(nearest, 1)[0]); } return sortedColors; }; var distinctColors = function distinctColors() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var options = _objectSpread({}, defaults, {}, opts); if (options.count <= 0) { return []; } if (options.samples < options.count * 3) { options.samples = Math.ceil(options.count * 3); } var colors = []; var zonesProto = []; var samples = new Set(); var rangeDivider = Math.ceil(Math.cbrt(options.samples)); var hStep = (options.hueMax - options.hueMin) / rangeDivider; var cStep = (options.chromaMax - options.chromaMin) / rangeDivider; var lStep = (options.lightMax - options.lightMin) / rangeDivider; if (hStep <= 0) { throw new Error('hueMax must be greater than hueMin!'); } if (cStep <= 0) { throw new Error('chromaMax must be greater than chromaMin!'); } if (lStep <= 0) { throw new Error('lightMax must be greater than lightMin!'); } for (var h = options.hueMin + hStep / 2; h <= options.hueMax; h += hStep) { for (var c = options.chromaMin + cStep / 2; c <= options.chromaMax; c += cStep) { for (var l = options.lightMin + lStep / 2; l <= options.lightMax; l += lStep) { var color = _chromaJs["default"].hcl(h, c, l).lab(); if (checkColor(color, options)) { samples.add(color.toString()); } } } } samples = Array.from(samples); samples = samples.map(function (i) { return i.split(',').map(function (j) { return parseFloat(j); }); }); if (samples.length < options.count) { throw new Error('Not enough samples to generate palette, increase sample count.'); } var sliceSize = Math.floor(samples.length / options.count); for (var i = 0; i < samples.length; i += sliceSize) { colors.push(samples[i]); zonesProto.push([]); if (colors.length >= options.count) { break; } } for (var step = 1; step <= options.quality; step += 1) { var zones = (0, _deepClone["default"])(zonesProto); var sampleList = (0, _deepClone["default"])(samples); // Immediately add the closest sample for each color for (var _i = 0; _i < colors.length; _i += 1) { var idx = getClosestIndex(sampleList, colors[_i]); zones[_i].push(sampleList[idx]); sampleList.splice(idx, 1); } // Find closest color for each remaining sample for (var _i2 = 0; _i2 < sampleList.length; _i2 += 1) { var sample = samples[_i2]; var nearest = getClosestIndex(colors, sample); zones[nearest].push(samples[_i2]); } var lastColors = (0, _deepClone["default"])(colors); for (var _i3 = 0; _i3 < zones.length; _i3 += 1) { var zone = zones[_i3]; var size = zone.length; var Ls = []; var As = []; var Bs = []; var _iterator = _createForOfIteratorHelper(zone), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _sample = _step.value; Ls.push(_sample[0]); As.push(_sample[1]); Bs.push(_sample[2]); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var lAvg = _utils["default"].sum(Ls) / size; var aAvg = _utils["default"].sum(As) / size; var bAvg = _utils["default"].sum(Bs) / size; colors[_i3] = [lAvg, aAvg, bAvg]; } if ((0, _deepEquals["default"])(lastColors, colors)) { break; } } colors = sortByContrast(colors); return colors.map(function (lab) { return _chromaJs["default"].lab(lab); }); }; var _default = distinctColors; exports["default"] = _default; },{"./utils":50,"chroma-js":45,"mout/lang/deepClone":357,"mout/lang/deepEquals":358}],50:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var utils = { sum: function sum(array) { return array.reduce(function (a, b) { return a + b; }); } }; var _default = utils; exports["default"] = _default; },{}],51:[function(require,module,exports){ 'use strict'; module.exports = earcut; module.exports.default = earcut; function earcut(data, holeIndices, dim) { dim = dim || 2; var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = []; if (!outerNode || outerNode.next === outerNode.prev) return triangles; var minX, minY, maxX, maxY, x, y, invSize; if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox if (data.length > 80 * dim) { minX = maxX = data[0]; minY = maxY = data[1]; for (var i = dim; i < outerLen; i += dim) { x = data[i]; y = data[i + 1]; if (x < minX) minX = x; if (y < minY) minY = y; if (x > maxX) maxX = x; if (y > maxY) maxY = y; } // minX, minY and invSize are later used to transform coords into integers for z-order calculation invSize = Math.max(maxX - minX, maxY - minY); invSize = invSize !== 0 ? 1 / invSize : 0; } earcutLinked(outerNode, triangles, dim, minX, minY, invSize); return triangles; } // create a circular doubly linked list from polygon points in the specified winding order function linkedList(data, start, end, dim, clockwise) { var i, last; if (clockwise === (signedArea(data, start, end, dim) > 0)) { for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); } else { for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); } if (last && equals(last, last.next)) { removeNode(last); last = last.next; } return last; } // eliminate colinear or duplicate points function filterPoints(start, end) { if (!start) return start; if (!end) end = start; var p = start, again; do { again = false; if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { removeNode(p); p = end = p.prev; if (p === p.next) break; again = true; } else { p = p.next; } } while (again || p !== end); return end; } // main ear slicing loop which triangulates a polygon (given as a linked list) function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { if (!ear) return; // interlink polygon nodes in z-order if (!pass && invSize) indexCurve(ear, minX, minY, invSize); var stop = ear, prev, next; // iterate through ears, slicing them one by one while (ear.prev !== ear.next) { prev = ear.prev; next = ear.next; if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { // cut off the triangle triangles.push(prev.i / dim); triangles.push(ear.i / dim); triangles.push(next.i / dim); removeNode(ear); // skipping the next vertex leads to less sliver triangles ear = next.next; stop = next.next; continue; } ear = next; // if we looped through the whole remaining polygon and can't find any more ears if (ear === stop) { // try filtering points and slicing again if (!pass) { earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally } else if (pass === 1) { ear = cureLocalIntersections(filterPoints(ear), triangles, dim); earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two } else if (pass === 2) { splitEarcut(ear, triangles, dim, minX, minY, invSize); } break; } } } // check whether a polygon node forms a valid ear with adjacent nodes function isEar(ear) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; // reflex, can't be an ear // now make sure we don't have other points inside the potential ear var p = ear.next.next; while (p !== ear.prev) { if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.next; } return true; } function isEarHashed(ear, minX, minY, invSize) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; // reflex, can't be an ear // triangle bbox; min & max are calculated like this for speed var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); // z-order range for the current triangle bbox; var minZ = zOrder(minTX, minTY, minX, minY, invSize), maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); var p = ear.prevZ, n = ear.nextZ; // look for points inside the triangle in both directions while (p && p.z >= minZ && n && n.z <= maxZ) { if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.prevZ; if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; n = n.nextZ; } // look for remaining points in decreasing z-order while (p && p.z >= minZ) { if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.prevZ; } // look for remaining points in increasing z-order while (n && n.z <= maxZ) { if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; n = n.nextZ; } return true; } // go through all polygon nodes and cure small local self-intersections function cureLocalIntersections(start, triangles, dim) { var p = start; do { var a = p.prev, b = p.next.next; if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { triangles.push(a.i / dim); triangles.push(p.i / dim); triangles.push(b.i / dim); // remove two nodes involved removeNode(p); removeNode(p.next); p = start = b; } p = p.next; } while (p !== start); return filterPoints(p); } // try splitting polygon into two and triangulate them independently function splitEarcut(start, triangles, dim, minX, minY, invSize) { // look for a valid diagonal that divides the polygon into two var a = start; do { var b = a.next.next; while (b !== a.prev) { if (a.i !== b.i && isValidDiagonal(a, b)) { // split the polygon in two by the diagonal var c = splitPolygon(a, b); // filter colinear points around the cuts a = filterPoints(a, a.next); c = filterPoints(c, c.next); // run earcut on each half earcutLinked(a, triangles, dim, minX, minY, invSize); earcutLinked(c, triangles, dim, minX, minY, invSize); return; } b = b.next; } a = a.next; } while (a !== start); } // link every hole into the outer loop, producing a single-ring polygon without holes function eliminateHoles(data, holeIndices, outerNode, dim) { var queue = [], i, len, start, end, list; for (i = 0, len = holeIndices.length; i < len; i++) { start = holeIndices[i] * dim; end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; list = linkedList(data, start, end, dim, false); if (list === list.next) list.steiner = true; queue.push(getLeftmost(list)); } queue.sort(compareX); // process holes from left to right for (i = 0; i < queue.length; i++) { eliminateHole(queue[i], outerNode); outerNode = filterPoints(outerNode, outerNode.next); } return outerNode; } function compareX(a, b) { return a.x - b.x; } // find a bridge between vertices that connects hole with an outer ring and and link it function eliminateHole(hole, outerNode) { outerNode = findHoleBridge(hole, outerNode); if (outerNode) { var b = splitPolygon(outerNode, hole); // filter collinear points around the cuts filterPoints(outerNode, outerNode.next); filterPoints(b, b.next); } } // David Eberly's algorithm for finding a bridge between hole and outer polygon function findHoleBridge(hole, outerNode) { var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m; // find a segment intersected by a ray from the hole's leftmost point to the left; // segment's endpoint with lesser x will be potential connection point do { if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); if (x <= hx && x > qx) { qx = x; if (x === hx) { if (hy === p.y) return p; if (hy === p.next.y) return p.next; } m = p.x < p.next.x ? p : p.next; } } p = p.next; } while (p !== outerNode); if (!m) return null; if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint // look for points inside the triangle of hole point, segment intersection and endpoint; // if there are no points found, we have a valid connection; // otherwise choose the point of the minimum angle with the ray as connection point var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan; p = m; do { if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { tan = Math.abs(hy - p.y) / (hx - p.x); // tangential if (locallyInside(p, hole) && (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { m = p; tanMin = tan; } } p = p.next; } while (p !== stop); return m; } // whether sector in vertex m contains sector in vertex p in the same coordinates function sectorContainsSector(m, p) { return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; } // interlink polygon nodes in z-order function indexCurve(start, minX, minY, invSize) { var p = start; do { if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); p.prevZ = p.prev; p.nextZ = p.next; p = p.next; } while (p !== start); p.prevZ.nextZ = null; p.prevZ = null; sortLinked(p); } // Simon Tatham's linked list merge sort algorithm // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html function sortLinked(list) { var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; do { p = list; list = null; tail = null; numMerges = 0; while (p) { numMerges++; q = p; pSize = 0; for (i = 0; i < inSize; i++) { pSize++; q = q.nextZ; if (!q) break; } qSize = inSize; while (pSize > 0 || (qSize > 0 && q)) { if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { e = p; p = p.nextZ; pSize--; } else { e = q; q = q.nextZ; qSize--; } if (tail) tail.nextZ = e; else list = e; e.prevZ = tail; tail = e; } p = q; } tail.nextZ = null; inSize *= 2; } while (numMerges > 1); return list; } // z-order of a point given coords and inverse of the longer side of data bbox function zOrder(x, y, minX, minY, invSize) { // coords are transformed into non-negative 15-bit integer range x = 32767 * (x - minX) * invSize; y = 32767 * (y - minY) * invSize; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; x = (x | (x << 2)) & 0x33333333; x = (x | (x << 1)) & 0x55555555; y = (y | (y << 8)) & 0x00FF00FF; y = (y | (y << 4)) & 0x0F0F0F0F; y = (y | (y << 2)) & 0x33333333; y = (y | (y << 1)) & 0x55555555; return x | (y << 1); } // find the leftmost node of a polygon ring function getLeftmost(start) { var p = start, leftmost = start; do { if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p; p = p.next; } while (p !== start); return leftmost; } // check if a point lies within a convex triangle function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; } // check if a diagonal between two polygon nodes is valid (lies in polygon interior) function isValidDiagonal(a, b) { return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case } // signed area of a triangle function area(p, q, r) { return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); } // check if two points are equal function equals(p1, p2) { return p1.x === p2.x && p1.y === p2.y; } // check if two segments intersect function intersects(p1, q1, p2, q2) { var o1 = sign(area(p1, q1, p2)); var o2 = sign(area(p1, q1, q2)); var o3 = sign(area(p2, q2, p1)); var o4 = sign(area(p2, q2, q1)); if (o1 !== o2 && o3 !== o4) return true; // general case if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 return false; } // for collinear points p, q, r, check if point q lies on segment pr function onSegment(p, q, r) { return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); } function sign(num) { return num > 0 ? 1 : num < 0 ? -1 : 0; } // check if a polygon diagonal intersects any polygon segments function intersectsPolygon(a, b) { var p = a; do { if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true; p = p.next; } while (p !== a); return false; } // check if a polygon diagonal is locally inside the polygon function locallyInside(a, b) { return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; } // check if the middle point of a polygon diagonal is inside the polygon function middleInside(a, b) { var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2; do { if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) inside = !inside; p = p.next; } while (p !== a); return inside; } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; // if one belongs to the outer ring and another to a hole, it merges it into a single ring function splitPolygon(a, b) { var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev; a.next = b; b.prev = a; a2.next = an; an.prev = a2; b2.next = a2; a2.prev = b2; bp.next = b2; b2.prev = bp; return b2; } // create a node and optionally link it with previous one (in a circular doubly linked list) function insertNode(i, x, y, last) { var p = new Node(i, x, y); if (!last) { p.prev = p; p.next = p; } else { p.next = last.next; p.prev = last; last.next.prev = p; last.next = p; } return p; } function removeNode(p) { p.next.prev = p.prev; p.prev.next = p.next; if (p.prevZ) p.prevZ.nextZ = p.nextZ; if (p.nextZ) p.nextZ.prevZ = p.prevZ; } function Node(i, x, y) { // vertex index in coordinates array this.i = i; // vertex coordinates this.x = x; this.y = y; // previous and next vertex nodes in a polygon ring this.prev = null; this.next = null; // z-order curve value this.z = null; // previous and next nodes in z-order this.prevZ = null; this.nextZ = null; // indicates whether this is a steiner point this.steiner = false; } // return a percentage difference between the polygon area and its triangulation area; // used to verify correctness of triangulation earcut.deviation = function (data, holeIndices, dim, triangles) { var hasHoles = holeIndices && holeIndices.length; var outerLen = hasHoles ? holeIndices[0] * dim : data.length; var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); if (hasHoles) { for (var i = 0, len = holeIndices.length; i < len; i++) { var start = holeIndices[i] * dim; var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; polygonArea -= Math.abs(signedArea(data, start, end, dim)); } } var trianglesArea = 0; for (i = 0; i < triangles.length; i += 3) { var a = triangles[i] * dim; var b = triangles[i + 1] * dim; var c = triangles[i + 2] * dim; trianglesArea += Math.abs( (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1])); } return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea); }; function signedArea(data, start, end, dim) { var sum = 0; for (var i = start, j = end - dim; i < end; i += dim) { sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); j = i; } return sum; } // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts earcut.flatten = function (data) { var dim = data[0][0].length, result = {vertices: [], holes: [], dimensions: dim}, holeIndex = 0; for (var i = 0; i < data.length; i++) { for (var j = 0; j < data[i].length; j++) { for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); } if (i > 0) { holeIndex += data[i - 1].length; result.holes.push(holeIndex); } } return result; }; },{}],52:[function(require,module,exports){ (function (global,setImmediate){ (function(global){ // // Check for native Promise and it has correct interface // var NativePromise = global['Promise']; var nativePromiseSupported = NativePromise && // Some of these methods are missing from // Firefox/Chrome experimental implementations 'resolve' in NativePromise && 'reject' in NativePromise && 'all' in NativePromise && 'race' in NativePromise && // Older version of the spec had a resolver object // as the arg rather than a function (function(){ var resolve; new NativePromise(function(r){ resolve = r; }); return typeof resolve === 'function'; })(); // // export if necessary // if (typeof exports !== 'undefined' && exports) { // node.js exports.Promise = nativePromiseSupported ? NativePromise : Promise; exports.Polyfill = Promise; } else { // AMD if (typeof define == 'function' && define.amd) { define(function(){ return nativePromiseSupported ? NativePromise : Promise; }); } else { // in browser add to global if (!nativePromiseSupported) global['Promise'] = Promise; } } // // Polyfill // var PENDING = 'pending'; var SEALED = 'sealed'; var FULFILLED = 'fulfilled'; var REJECTED = 'rejected'; var NOOP = function(){}; function isArray(value) { return Object.prototype.toString.call(value) === '[object Array]'; } // async calls var asyncSetTimer = typeof setImmediate !== 'undefined' ? setImmediate : setTimeout; var asyncQueue = []; var asyncTimer; function asyncFlush(){ // run promise callbacks for (var i = 0; i < asyncQueue.length; i++) asyncQueue[i][0](asyncQueue[i][1]); // reset async asyncQueue asyncQueue = []; asyncTimer = false; } function asyncCall(callback, arg){ asyncQueue.push([callback, arg]); if (!asyncTimer) { asyncTimer = true; asyncSetTimer(asyncFlush, 0); } } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(subscriber){ var owner = subscriber.owner; var settled = owner.state_; var value = owner.data_; var callback = subscriber[settled]; var promise = subscriber.then; if (typeof callback === 'function') { settled = FULFILLED; try { value = callback(value); } catch(e) { reject(promise, e); } } if (!handleThenable(promise, value)) { if (settled === FULFILLED) resolve(promise, value); if (settled === REJECTED) reject(promise, value); } } function handleThenable(promise, value) { var resolved; try { if (promise === value) throw new TypeError('A promises callback cannot return that same promise.'); if (value && (typeof value === 'function' || typeof value === 'object')) { var then = value.then; // then should be retrived only once if (typeof then === 'function') { then.call(value, function(val){ if (!resolved) { resolved = true; if (value !== val) resolve(promise, val); else fulfill(promise, val); } }, function(reason){ if (!resolved) { resolved = true; reject(promise, reason); } }); return true; } } } catch (e) { if (!resolved) reject(promise, e); return true; } return false; } function resolve(promise, value){ if (promise === value || !handleThenable(promise, value)) fulfill(promise, value); } function fulfill(promise, value){ if (promise.state_ === PENDING) { promise.state_ = SEALED; promise.data_ = value; asyncCall(publishFulfillment, promise); } } function reject(promise, reason){ if (promise.state_ === PENDING) { promise.state_ = SEALED; promise.data_ = reason; asyncCall(publishRejection, promise); } } function publish(promise) { var callbacks = promise.then_; promise.then_ = undefined; for (var i = 0; i < callbacks.length; i++) { invokeCallback(callbacks[i]); } } function publishFulfillment(promise){ promise.state_ = FULFILLED; publish(promise); } function publishRejection(promise){ promise.state_ = REJECTED; publish(promise); } /** * @class */ function Promise(resolver){ if (typeof resolver !== 'function') throw new TypeError('Promise constructor takes a function argument'); if (this instanceof Promise === false) throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); this.then_ = []; invokeResolver(resolver, this); } Promise.prototype = { constructor: Promise, state_: PENDING, then_: null, data_: undefined, then: function(onFulfillment, onRejection){ var subscriber = { owner: this, then: new this.constructor(NOOP), fulfilled: onFulfillment, rejected: onRejection }; if (this.state_ === FULFILLED || this.state_ === REJECTED) { // already resolved, call callback async asyncCall(invokeCallback, subscriber); } else { // subscribe this.then_.push(subscriber); } return subscriber.then; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = function(promises){ var Class = this; if (!isArray(promises)) throw new TypeError('You must pass an array to Promise.all().'); return new Class(function(resolve, reject){ var results = []; var remaining = 0; function resolver(index){ remaining++; return function(value){ results[index] = value; if (!--remaining) resolve(results); }; } for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') promise.then(resolver(i), reject); else results[i] = promise; } if (!remaining) resolve(results); }); }; Promise.race = function(promises){ var Class = this; if (!isArray(promises)) throw new TypeError('You must pass an array to Promise.race().'); return new Class(function(resolve, reject) { for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') promise.then(resolve, reject); else resolve(promise); } }); }; Promise.resolve = function(value){ var Class = this; if (value && typeof value === 'object' && value.constructor === Class) return value; return new Class(function(resolve){ resolve(value); }); }; Promise.reject = function(reason){ var Class = this; return new Class(function(resolve, reject){ reject(reason); }); }; })(typeof window != 'undefined' ? window : typeof global != 'undefined' ? global : typeof self != 'undefined' ? self : this); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) },{"timers":393}],53:[function(require,module,exports){ 'use strict'; var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // if ('undefined' !== typeof module) { module.exports = EventEmitter; } },{}],54:[function(require,module,exports){ module.exports = stringify stringify.default = stringify stringify.stable = deterministicStringify stringify.stableStringify = deterministicStringify var arr = [] var replacerStack = [] // Regular stringify function stringify (obj, replacer, spacer) { decirc(obj, '', [], undefined) var res if (replacerStack.length === 0) { res = JSON.stringify(obj, replacer, spacer) } else { res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) } while (arr.length !== 0) { var part = arr.pop() if (part.length === 4) { Object.defineProperty(part[0], part[1], part[3]) } else { part[0][part[1]] = part[2] } } return res } function decirc (val, k, stack, parent) { var i if (typeof val === 'object' && val !== null) { for (i = 0; i < stack.length; i++) { if (stack[i] === val) { var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) if (propertyDescriptor.get !== undefined) { if (propertyDescriptor.configurable) { Object.defineProperty(parent, k, { value: '[Circular]' }) arr.push([parent, k, val, propertyDescriptor]) } else { replacerStack.push([val, k]) } } else { parent[k] = '[Circular]' arr.push([parent, k, val]) } return } } stack.push(val) // Optimize for Arrays. Big arrays could kill the performance otherwise! if (Array.isArray(val)) { for (i = 0; i < val.length; i++) { decirc(val[i], i, stack, val) } } else { var keys = Object.keys(val) for (i = 0; i < keys.length; i++) { var key = keys[i] decirc(val[key], key, stack, val) } } stack.pop() } } // Stable-stringify function compareFunction (a, b) { if (a < b) { return -1 } if (a > b) { return 1 } return 0 } function deterministicStringify (obj, replacer, spacer) { var tmp = deterministicDecirc(obj, '', [], undefined) || obj var res if (replacerStack.length === 0) { res = JSON.stringify(tmp, replacer, spacer) } else { res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) } while (arr.length !== 0) { var part = arr.pop() if (part.length === 4) { Object.defineProperty(part[0], part[1], part[3]) } else { part[0][part[1]] = part[2] } } return res } function deterministicDecirc (val, k, stack, parent) { var i if (typeof val === 'object' && val !== null) { for (i = 0; i < stack.length; i++) { if (stack[i] === val) { var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) if (propertyDescriptor.get !== undefined) { if (propertyDescriptor.configurable) { Object.defineProperty(parent, k, { value: '[Circular]' }) arr.push([parent, k, val, propertyDescriptor]) } else { replacerStack.push([val, k]) } } else { parent[k] = '[Circular]' arr.push([parent, k, val]) } return } } if (typeof val.toJSON === 'function') { return } stack.push(val) // Optimize for Arrays. Big arrays could kill the performance otherwise! if (Array.isArray(val)) { for (i = 0; i < val.length; i++) { deterministicDecirc(val[i], i, stack, val) } } else { // Create a temporary object in the required way var tmp = {} var keys = Object.keys(val).sort(compareFunction) for (i = 0; i < keys.length; i++) { var key = keys[i] deterministicDecirc(val[key], key, stack, val) tmp[key] = val[key] } if (parent !== undefined) { arr.push([parent, k, val]) parent[k] = tmp } else { return tmp } } stack.pop() } } // wraps replacer function to handle values we couldn't replace // and mark them as [Circular] function replaceGetterValues (replacer) { replacer = replacer !== undefined ? replacer : function (k, v) { return v } return function (key, val) { if (replacerStack.length > 0) { for (var i = 0; i < replacerStack.length; i++) { var part = replacerStack[i] if (part[1] === key && part[0] === val) { val = '[Circular]' replacerStack.splice(i, 1) break } } } return replacer.call(this, key, val) } } },{}],55:[function(require,module,exports){ (function (root, factory) { // Hack to make all exports of this module sha256 function object properties. var exports = {}; factory(exports); var sha256 = exports["default"]; for (var k in exports) { sha256[k] = exports[k]; } if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = sha256; } else if (typeof define === 'function' && define.amd) { define(function() { return sha256; }); } else { root.sha256 = sha256; } })(this, function(exports) { "use strict"; exports.__esModule = true; // SHA-256 (+ HMAC and PBKDF2) for JavaScript. // // Written in 2014-2016 by Dmitry Chestnykh. // Public domain, no warranty. // // Functions (accept and return Uint8Arrays): // // sha256(message) -> hash // sha256.hmac(key, message) -> mac // sha256.pbkdf2(password, salt, rounds, dkLen) -> dk // // Classes: // // new sha256.Hash() // new sha256.HMAC(key) // exports.digestLength = 32; exports.blockSize = 64; // SHA-256 constants var K = new Uint32Array([ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]); function hashBlocks(w, v, p, pos, len) { var a, b, c, d, e, f, g, h, u, i, j, t1, t2; while (len >= 64) { a = v[0]; b = v[1]; c = v[2]; d = v[3]; e = v[4]; f = v[5]; g = v[6]; h = v[7]; for (i = 0; i < 16; i++) { j = pos + i * 4; w[i] = (((p[j] & 0xff) << 24) | ((p[j + 1] & 0xff) << 16) | ((p[j + 2] & 0xff) << 8) | (p[j + 3] & 0xff)); } for (i = 16; i < 64; i++) { u = w[i - 2]; t1 = (u >>> 17 | u << (32 - 17)) ^ (u >>> 19 | u << (32 - 19)) ^ (u >>> 10); u = w[i - 15]; t2 = (u >>> 7 | u << (32 - 7)) ^ (u >>> 18 | u << (32 - 18)) ^ (u >>> 3); w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0); } for (i = 0; i < 64; i++) { t1 = (((((e >>> 6 | e << (32 - 6)) ^ (e >>> 11 | e << (32 - 11)) ^ (e >>> 25 | e << (32 - 25))) + ((e & f) ^ (~e & g))) | 0) + ((h + ((K[i] + w[i]) | 0)) | 0)) | 0; t2 = (((a >>> 2 | a << (32 - 2)) ^ (a >>> 13 | a << (32 - 13)) ^ (a >>> 22 | a << (32 - 22))) + ((a & b) ^ (a & c) ^ (b & c))) | 0; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } v[0] += a; v[1] += b; v[2] += c; v[3] += d; v[4] += e; v[5] += f; v[6] += g; v[7] += h; pos += 64; len -= 64; } return pos; } // Hash implements SHA256 hash algorithm. var Hash = /** @class */ (function () { function Hash() { this.digestLength = exports.digestLength; this.blockSize = exports.blockSize; // Note: Int32Array is used instead of Uint32Array for performance reasons. this.state = new Int32Array(8); // hash state this.temp = new Int32Array(64); // temporary state this.buffer = new Uint8Array(128); // buffer for data to hash this.bufferLength = 0; // number of bytes in buffer this.bytesHashed = 0; // number of total bytes hashed this.finished = false; // indicates whether the hash was finalized this.reset(); } // Resets hash state making it possible // to re-use this instance to hash other data. Hash.prototype.reset = function () { this.state[0] = 0x6a09e667; this.state[1] = 0xbb67ae85; this.state[2] = 0x3c6ef372; this.state[3] = 0xa54ff53a; this.state[4] = 0x510e527f; this.state[5] = 0x9b05688c; this.state[6] = 0x1f83d9ab; this.state[7] = 0x5be0cd19; this.bufferLength = 0; this.bytesHashed = 0; this.finished = false; return this; }; // Cleans internal buffers and re-initializes hash state. Hash.prototype.clean = function () { for (var i = 0; i < this.buffer.length; i++) { this.buffer[i] = 0; } for (var i = 0; i < this.temp.length; i++) { this.temp[i] = 0; } this.reset(); }; // Updates hash state with the given data. // // Optionally, length of the data can be specified to hash // fewer bytes than data.length. // // Throws error when trying to update already finalized hash: // instance must be reset to use it again. Hash.prototype.update = function (data, dataLength) { if (dataLength === void 0) { dataLength = data.length; } if (this.finished) { throw new Error("SHA256: can't update because hash was finished."); } var dataPos = 0; this.bytesHashed += dataLength; if (this.bufferLength > 0) { while (this.bufferLength < 64 && dataLength > 0) { this.buffer[this.bufferLength++] = data[dataPos++]; dataLength--; } if (this.bufferLength === 64) { hashBlocks(this.temp, this.state, this.buffer, 0, 64); this.bufferLength = 0; } } if (dataLength >= 64) { dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength); dataLength %= 64; } while (dataLength > 0) { this.buffer[this.bufferLength++] = data[dataPos++]; dataLength--; } return this; }; // Finalizes hash state and puts hash into out. // // If hash was already finalized, puts the same value. Hash.prototype.finish = function (out) { if (!this.finished) { var bytesHashed = this.bytesHashed; var left = this.bufferLength; var bitLenHi = (bytesHashed / 0x20000000) | 0; var bitLenLo = bytesHashed << 3; var padLength = (bytesHashed % 64 < 56) ? 64 : 128; this.buffer[left] = 0x80; for (var i = left + 1; i < padLength - 8; i++) { this.buffer[i] = 0; } this.buffer[padLength - 8] = (bitLenHi >>> 24) & 0xff; this.buffer[padLength - 7] = (bitLenHi >>> 16) & 0xff; this.buffer[padLength - 6] = (bitLenHi >>> 8) & 0xff; this.buffer[padLength - 5] = (bitLenHi >>> 0) & 0xff; this.buffer[padLength - 4] = (bitLenLo >>> 24) & 0xff; this.buffer[padLength - 3] = (bitLenLo >>> 16) & 0xff; this.buffer[padLength - 2] = (bitLenLo >>> 8) & 0xff; this.buffer[padLength - 1] = (bitLenLo >>> 0) & 0xff; hashBlocks(this.temp, this.state, this.buffer, 0, padLength); this.finished = true; } for (var i = 0; i < 8; i++) { out[i * 4 + 0] = (this.state[i] >>> 24) & 0xff; out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff; out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff; out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff; } return this; }; // Returns the final hash digest. Hash.prototype.digest = function () { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; // Internal function for use in HMAC for optimization. Hash.prototype._saveState = function (out) { for (var i = 0; i < this.state.length; i++) { out[i] = this.state[i]; } }; // Internal function for use in HMAC for optimization. Hash.prototype._restoreState = function (from, bytesHashed) { for (var i = 0; i < this.state.length; i++) { this.state[i] = from[i]; } this.bytesHashed = bytesHashed; this.finished = false; this.bufferLength = 0; }; return Hash; }()); exports.Hash = Hash; // HMAC implements HMAC-SHA256 message authentication algorithm. var HMAC = /** @class */ (function () { function HMAC(key) { this.inner = new Hash(); this.outer = new Hash(); this.blockSize = this.inner.blockSize; this.digestLength = this.inner.digestLength; var pad = new Uint8Array(this.blockSize); if (key.length > this.blockSize) { (new Hash()).update(key).finish(pad).clean(); } else { for (var i = 0; i < key.length; i++) { pad[i] = key[i]; } } for (var i = 0; i < pad.length; i++) { pad[i] ^= 0x36; } this.inner.update(pad); for (var i = 0; i < pad.length; i++) { pad[i] ^= 0x36 ^ 0x5c; } this.outer.update(pad); this.istate = new Uint32Array(8); this.ostate = new Uint32Array(8); this.inner._saveState(this.istate); this.outer._saveState(this.ostate); for (var i = 0; i < pad.length; i++) { pad[i] = 0; } } // Returns HMAC state to the state initialized with key // to make it possible to run HMAC over the other data with the same // key without creating a new instance. HMAC.prototype.reset = function () { this.inner._restoreState(this.istate, this.inner.blockSize); this.outer._restoreState(this.ostate, this.outer.blockSize); return this; }; // Cleans HMAC state. HMAC.prototype.clean = function () { for (var i = 0; i < this.istate.length; i++) { this.ostate[i] = this.istate[i] = 0; } this.inner.clean(); this.outer.clean(); }; // Updates state with provided data. HMAC.prototype.update = function (data) { this.inner.update(data); return this; }; // Finalizes HMAC and puts the result in out. HMAC.prototype.finish = function (out) { if (this.outer.finished) { this.outer.finish(out); } else { this.inner.finish(out); this.outer.update(out, this.digestLength).finish(out); } return this; }; // Returns message authentication code. HMAC.prototype.digest = function () { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; return HMAC; }()); exports.HMAC = HMAC; // Returns SHA256 hash of data. function hash(data) { var h = (new Hash()).update(data); var digest = h.digest(); h.clean(); return digest; } exports.hash = hash; // Function hash is both available as module.hash and as default export. exports["default"] = hash; // Returns HMAC-SHA256 of data under the key. function hmac(key, data) { var h = (new HMAC(key)).update(data); var digest = h.digest(); h.clean(); return digest; } exports.hmac = hmac; // Fills hkdf buffer like this: // T(1) = HMAC-Hash(PRK, T(0) | info | 0x01) function fillBuffer(buffer, hmac, info, counter) { // Counter is a byte value: check if it overflowed. var num = counter[0]; if (num === 0) { throw new Error("hkdf: cannot expand more"); } // Prepare HMAC instance for new data with old key. hmac.reset(); // Hash in previous output if it was generated // (i.e. counter is greater than 1). if (num > 1) { hmac.update(buffer); } // Hash in info if it exists. if (info) { hmac.update(info); } // Hash in the counter. hmac.update(counter); // Output result to buffer and clean HMAC instance. hmac.finish(buffer); // Increment counter inside typed array, this works properly. counter[0]++; } var hkdfSalt = new Uint8Array(exports.digestLength); // Filled with zeroes. function hkdf(key, salt, info, length) { if (salt === void 0) { salt = hkdfSalt; } if (length === void 0) { length = 32; } var counter = new Uint8Array([1]); // HKDF-Extract uses salt as HMAC key, and key as data. var okm = hmac(salt, key); // Initialize HMAC for expanding with extracted key. // Ensure no collisions with `hmac` function. var hmac_ = new HMAC(okm); // Allocate buffer. var buffer = new Uint8Array(hmac_.digestLength); var bufpos = buffer.length; var out = new Uint8Array(length); for (var i = 0; i < length; i++) { if (bufpos === buffer.length) { fillBuffer(buffer, hmac_, info, counter); bufpos = 0; } out[i] = buffer[bufpos++]; } hmac_.clean(); buffer.fill(0); counter.fill(0); return out; } exports.hkdf = hkdf; // Derives a key from password and salt using PBKDF2-HMAC-SHA256 // with the given number of iterations. // // The number of bytes returned is equal to dkLen. // // (For better security, avoid dkLen greater than hash length - 32 bytes). function pbkdf2(password, salt, iterations, dkLen) { var prf = new HMAC(password); var len = prf.digestLength; var ctr = new Uint8Array(4); var t = new Uint8Array(len); var u = new Uint8Array(len); var dk = new Uint8Array(dkLen); for (var i = 0; i * len < dkLen; i++) { var c = i + 1; ctr[0] = (c >>> 24) & 0xff; ctr[1] = (c >>> 16) & 0xff; ctr[2] = (c >>> 8) & 0xff; ctr[3] = (c >>> 0) & 0xff; prf.reset(); prf.update(salt); prf.update(ctr); prf.finish(u); for (var j = 0; j < len; j++) { t[j] = u[j]; } for (var j = 2; j <= iterations; j++) { prf.reset(); prf.update(u).finish(u); for (var k = 0; k < len; k++) { t[k] ^= u[k]; } } for (var j = 0; j < len && i * len + j < dkLen; j++) { dk[i * len + j] = t[j]; } } for (var i = 0; i < len; i++) { t[i] = u[i] = 0; } for (var i = 0; i < 4; i++) { ctr[i] = 0; } prf.clean(); return dk; } exports.pbkdf2 = pbkdf2; }); },{}],56:[function(require,module,exports){ /** * Graphology Components * ====================== * * Basic connected components-related functions. */ var isGraph = require('graphology-utils/is-graph'); /** * Function returning a list of connected components. * * @param {Graph} graph - Target graph. * @return {array} */ exports.connectedComponents = function(graph) { if (!isGraph(graph)) throw new Error('graphology-components: the given graph is not a valid graphology instance.'); if (!graph.order) return []; var components = [], nodes = graph.nodes(), i, l; if (!graph.size) { for (i = 0, l = nodes.length; i < l; i++) { components.push([nodes[i]]); } return components; } var component, stack = [], node, neighbor, visited = new Set(); for (i = 0, l = nodes.length; i < l; i++) { node = nodes[i]; if (!visited.has(node)) { visited.add(node); component = [node]; components.push(component); stack.push.apply(stack, graph.neighbors(node)); while (stack.length) { neighbor = stack.pop(); if (!visited.has(neighbor)) { visited.add(neighbor); component.push(neighbor); stack.push.apply(stack, graph.neighbors(neighbor)); } } } } return components; }; /** * Function returning a list of strongly connected components. * * @param {Graph} graph - Target directed graph. * @return {array} */ exports.stronglyConnectedComponents = function(graph) { if (!isGraph(graph)) throw new Error('graphology-components: the given graph is not a valid graphology instance.'); if (!graph.order) return []; if (graph.type === 'undirected') throw new Error('graphology-components: the given graph is undirected'); var nodes = graph.nodes(), components = [], i, l; if (!graph.size) { for (i = 0, l = nodes.length; i < l; i++) components.push([nodes[i]]); return components; } var count = 1, P = [], S = [], preorder = new Map(), assigned = new Set(), component, pop, vertex; var DFS = function(node) { var neighbor, neighbors = graph.outNeighbors(node).concat(graph.undirectedNeighbors(node)), neighborOrder; preorder.set(node, count++); P.push(node); S.push(node); for (var k = 0, n = neighbors.length; k < n; k++) { neighbor = neighbors[k]; if (preorder.has(neighbor)) { neighborOrder = preorder.get(neighbor); if (!assigned.has(neighbor)) while (preorder.get(P[P.length - 1]) > neighborOrder) P.pop(); } else DFS(neighbor); } if (preorder.get(P[P.length - 1]) === preorder.get(node)) { component = []; do { pop = S.pop(); component.push(pop); assigned.add(pop); } while (pop !== node); components.push(component); P.pop(); } }; for (i = 0, l = nodes.length; i < l; i++) { vertex = nodes[i]; if (!assigned.has(vertex)) DFS(vertex); } return components; }; },{"graphology-utils/is-graph":108}],57:[function(require,module,exports){ /** * Graphology Complete Graph Generator * ==================================== * * Function generating complete graphs. */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'), combinations = require('obliterator/combinations'), range = require('lodash/range'); /** * Generates a complete graph with n nodes. * * @param {Class} GraphClass - The Graph Class to instantiate. * @param {number} order - Number of nodes of the graph. * @return {Graph} */ module.exports = function complete(GraphClass, order) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/classic/complete: invalid Graph constructor.'); var graph = new GraphClass(); for (var i = 0; i < order; i++) graph.addNode(i); if (order > 1) { var iterator = combinations(range(order), 2), path, step; while ((step = iterator.next(), !step.done)) { path = step.value; if (graph.type !== 'directed') graph.addUndirectedEdge(path[0], path[1]); if (graph.type !== 'undirected') { graph.addDirectedEdge(path[0], path[1]); graph.addDirectedEdge(path[1], path[0]); } } } return graph; }; },{"graphology-utils/is-graph-constructor":107,"lodash/range":217,"obliterator/combinations":373}],58:[function(require,module,exports){ /** * Graphology Empty Graph Generator * ================================= * * Function generating empty graphs. */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'); /** * Generates an empty graph with n nodes and 0 edges. * * @param {Class} GraphClass - The Graph Class to instantiate. * @param {number} order - Number of nodes of the graph. * @return {Graph} */ module.exports = function empty(GraphClass, order) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/classic/empty: invalid Graph constructor.'); var graph = new GraphClass(); var i; for (i = 0; i < order; i++) graph.addNode(i); return graph; }; },{"graphology-utils/is-graph-constructor":107}],59:[function(require,module,exports){ /** * Graphology Classic Graph Generators * ==================================== * * Classic graph generators endpoint. */ exports.complete = require('./complete.js'); exports.empty = require('./empty.js'); exports.ladder = require('./ladder.js'); exports.path = require('./path.js'); },{"./complete.js":57,"./empty.js":58,"./ladder.js":60,"./path.js":61}],60:[function(require,module,exports){ /** * Graphology Ladder Graph Generator * ================================== * * Function generating ladder graphs. */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'), mergePath = require('graphology-utils/merge-path'), range = require('lodash/range'); /** * Generates a ladder graph of length n (order will therefore be 2 * n). * * @param {Class} GraphClass - The Graph Class to instantiate. * @param {number} length - Length of the ladder. * @return {Graph} */ module.exports = function ladder(GraphClass, length) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/classic/ladder: invalid Graph constructor.'); var graph = new GraphClass(); mergePath(graph, range(length)); mergePath(graph, range(length, length * 2)); for (var i = 0; i < length; i++) graph.addEdge(i, i + length); return graph; }; },{"graphology-utils/is-graph-constructor":107,"graphology-utils/merge-path":109,"lodash/range":217}],61:[function(require,module,exports){ /** * Graphology Path Graph Generator * ================================ * * Function generating path graphs. */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'), mergePath = require('graphology-utils/merge-path'), range = require('lodash/range'); /** * Generates a path graph with n nodes. * * @param {Class} GraphClass - The Graph Class to instantiate. * @param {number} order - Number of nodes of the graph. * @return {Graph} */ module.exports = function path(GraphClass, order) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/classic/path: invalid Graph constructor.'); var graph = new GraphClass(); mergePath(graph, range(order)); return graph; }; },{"graphology-utils/is-graph-constructor":107,"graphology-utils/merge-path":109,"lodash/range":217}],62:[function(require,module,exports){ /** * Graphology Caveman Graph Generator * =================================== * * Function generating caveman graphs. * * [Article]: * Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.' * Amer. J. Soc. 105, 493-527, 1999. */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'), empty = require('../classic/empty.js'); /** * Function returning a caveman graph with desired properties. * * @param {Class} GraphClass - The Graph Class to instantiate. * @param {number} l - The number of cliques in the graph. * @param {number} k - Size of the cliques. * @return {Graph} */ module.exports = function caveman(GraphClass, l, k) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/community/caveman: invalid Graph constructor.'); var m = l * k; var graph = empty(GraphClass, m); if (k < 2) return graph; var i, j, s; for (i = 0; i < m; i += k) { for (j = i; j < i + k; j++) { for (s = j + 1; s < i + k; s++) graph.addEdge(j, s); } } return graph; }; },{"../classic/empty.js":58,"graphology-utils/is-graph-constructor":107}],63:[function(require,module,exports){ /** * Graphology Connected Caveman Graph Generator * ============================================= * * Function generating connected caveman graphs. * * [Article]: * Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.' * Amer. J. Soc. 105, 493-527, 1999. */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'), empty = require('../classic/empty.js'); /** * Function returning a connected caveman graph with desired properties. * * @param {Class} GraphClass - The Graph Class to instantiate. * @param {number} l - The number of cliques in the graph. * @param {number} k - Size of the cliques. * @return {Graph} */ module.exports = function connectedCaveman(GraphClass, l, k) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/community/connected-caveman: invalid Graph constructor.'); var m = l * k; var graph = empty(GraphClass, m); if (k < 2) return graph; var i, j, s; for (i = 0; i < m; i += k) { for (j = i; j < i + k; j++) { for (s = j + 1; s < i + k; s++) { if (j !== i || j !== s - 1) graph.addEdge(j, s); } } if (i > 0) graph.addEdge(i, (i - 1) % m); } graph.addEdge(0, m - 1); return graph; }; },{"../classic/empty.js":58,"graphology-utils/is-graph-constructor":107}],64:[function(require,module,exports){ /** * Graphology Community Graph Generators * ====================================== * * Community graph generators endpoint. */ exports.caveman = require('./caveman.js'); exports.connectedCaveman = require('./connected-caveman.js'); },{"./caveman.js":62,"./connected-caveman.js":63}],65:[function(require,module,exports){ /** * Graphology Random Clusters Graph Generator * =========================================== * * Function generating a graph containing the desired number of nodes & edges * and organized in the desired number of clusters. * * [Author]: * Alexis Jacomy */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'); /** * Generates a random graph with clusters. * * @param {Class} GraphClass - The Graph Class to instantiate. * @param {object} options - Options: * @param {number} clusterDensity - Probability that an edge will link two * nodes of the same cluster. * @param {number} order - Number of nodes. * @param {number} size - Number of edges. * @param {number} clusters - Number of clusters. * @param {function} rng - Custom RNG function. * @return {Graph} */ module.exports = function(GraphClass, options) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/random/clusters: invalid Graph constructor.'); options = options || {}; var clusterDensity = ('clusterDensity' in options) ? options.clusterDensity : 0.5, rng = options.rng || Math.random, N = options.order, E = options.size, C = options.clusters; if (typeof clusterDensity !== 'number' || clusterDensity > 1 || clusterDensity < 0) throw new Error('graphology-generators/random/clusters: `clusterDensity` option should be a number between 0 and 1.'); if (typeof rng !== 'function') throw new Error('graphology-generators/random/clusters: `rng` option should be a function.'); if (typeof N !== 'number' || N <= 0) throw new Error('graphology-generators/random/clusters: `order` option should be a positive number.'); if (typeof E !== 'number' || E <= 0) throw new Error('graphology-generators/random/clusters: `size` option should be a positive number.'); if (typeof C !== 'number' || C <= 0) throw new Error('graphology-generators/random/clusters: `clusters` option should be a positive number.'); // Creating graph var graph = new GraphClass(); // Adding nodes if (!N) return graph; // Initializing clusters var clusters = new Array(C), cluster, nodes, i; for (i = 0; i < C; i++) clusters[i] = []; for (i = 0; i < N; i++) { cluster = (rng() * C) | 0; graph.addNode(i, {cluster: cluster}); clusters[cluster].push(i); } // Adding edges if (!E) return graph; var source, target, l; for (i = 0; i < E; i++) { // Adding a link between two random nodes if (rng() < 1 - clusterDensity) { source = (rng() * N) | 0; do { target = (rng() * N) | 0; } while (source === target); } // Adding a link between two nodes from the same cluster else { cluster = (rng() * C) | 0; nodes = clusters[cluster]; l = nodes.length; if (!l || l < 2) { // TODO: in those case we may have fewer edges than required // TODO: check where E is over full clusterDensity continue; } source = nodes[(rng() * l) | 0]; do { target = nodes[(rng() * l) | 0]; } while (source === target); } if (!graph.multi) graph.mergeEdge(source, target); else graph.addEdge(source, target); } return graph; }; },{"graphology-utils/is-graph-constructor":107}],66:[function(require,module,exports){ /** * Graphology Erdos-Renyi Graph Generator * ======================================= * * Function generating binomial graphs. */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'), combinations = require('obliterator/combinations'), range = require('lodash/range'), density = require('graphology-metrics/density'); /** * Generates a binomial graph graph with n nodes. * * @param {Class} GraphClass - The Graph Class to instantiate. * @param {object} options - Options: * @param {number} order - Number of nodes in the graph. * @param {number} probability - Probability for edge creation. * @param {function} rng - Custom RNG function. * @return {Graph} */ function erdosRenyi(GraphClass, options) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/random/erdos-renyi: invalid Graph constructor.'); var order = options.order, probability = options.probability, rng = options.rng || Math.random; var graph = new GraphClass(); // If user gave a size, we need to compute probability if (typeof options.approximateSize === 'number') { var densityFunction = density[graph.type + 'Density']; probability = densityFunction(order, options.approximateSize); } if (typeof order !== 'number' || order <= 0) throw new Error('graphology-generators/random/erdos-renyi: invalid `order`. Should be a positive number.'); if (typeof probability !== 'number' || probability < 0 || probability > 1) throw new Error('graphology-generators/random/erdos-renyi: invalid `probability`. Should be a number between 0 and 1. Or maybe you gave an `approximateSize` exceeding the graph\'s density.'); if (typeof rng !== 'function') throw new Error('graphology-generators/random/erdos-renyi: invalid `rng`. Should be a function.'); for (var i = 0; i < order; i++) graph.addNode(i); if (probability <= 0) return graph; if (order > 1) { var iterator = combinations(range(order), 2), path, step; while ((step = iterator.next(), !step.done)) { path = step.value; if (graph.type !== 'directed') { if (rng() < probability) graph.addUndirectedEdge(path[0], path[1]); } if (graph.type !== 'undirected') { if (rng() < probability) graph.addDirectedEdge(path[0], path[1]); if (rng() < probability) graph.addDirectedEdge(path[1], path[0]); } } } return graph; } /** * Generates a binomial graph graph with n nodes using a faster algorithm * for sparse graphs. * * @param {Class} GraphClass - The Graph Class to instantiate. * @param {object} options - Options: * @param {number} order - Number of nodes in the graph. * @param {number} probability - Probability for edge creation. * @param {function} rng - Custom RNG function. * @return {Graph} */ function erdosRenyiSparse(GraphClass, options) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/random/erdos-renyi: invalid Graph constructor.'); var order = options.order, probability = options.probability, rng = options.rng || Math.random; var graph = new GraphClass(); // If user gave a size, we need to compute probability if (typeof options.approximateSize === 'number') { var densityFunction = density[graph.type + 'Density']; probability = densityFunction(order, options.approximateSize); } if (typeof order !== 'number' || order <= 0) throw new Error('graphology-generators/random/erdos-renyi: invalid `order`. Should be a positive number.'); if (typeof probability !== 'number' || probability < 0 || probability > 1) throw new Error('graphology-generators/random/erdos-renyi: invalid `probability`. Should be a number between 0 and 1. Or maybe you gave an `approximateSize` exceeding the graph\'s density.'); if (typeof rng !== 'function') throw new Error('graphology-generators/random/erdos-renyi: invalid `rng`. Should be a function.'); for (var i = 0; i < order; i++) graph.addNode(i); if (probability <= 0) return graph; var w = -1, lp = Math.log(1 - probability), lr, v; if (graph.type !== 'undirected') { v = 0; while (v < order) { lr = Math.log(1 - rng()); w += 1 + ((lr / lp) | 0); // Avoiding self loops if (v === w) { w++; } while (v < order && order <= w) { w -= order; v++; // Avoiding self loops if (v === w) w++; } if (v < order) graph.addDirectedEdge(v, w); } } w = -1; if (graph.type !== 'directed') { v = 1; while (v < order) { lr = Math.log(1 - rng()); w += 1 + ((lr / lp) | 0); while (w >= v && v < order) { w -= v; v++; } if (v < order) graph.addUndirectedEdge(v, w); } } return graph; } /** * Exporting. */ erdosRenyi.sparse = erdosRenyiSparse; module.exports = erdosRenyi; },{"graphology-metrics/density":85,"graphology-utils/is-graph-constructor":107,"lodash/range":217,"obliterator/combinations":373}],67:[function(require,module,exports){ /** * Graphology Girvan-Newman Graph Generator * ========================================= * * Function generating graphs liks the one used to test the Girvan-Newman * community algorithm. * * [Reference]: * http://www.pnas.org/content/99/12/7821.full.pdf * * [Article]: * Community Structure in social and biological networks. * Girvan Newman, 2002. PNAS June, vol 99 n 12 */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'); /** * Generates a binomial graph graph with n nodes. * * @param {Class} GraphClass - The Graph Class to instantiate. * @param {object} options - Options: * @param {number} zOut - zOut parameter. * @param {function} rng - Custom RNG function. * @return {Graph} */ module.exports = function girvanNewman(GraphClass, options) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/random/girvan-newman: invalid Graph constructor.'); var zOut = options.zOut, rng = options.rng || Math.random; if (typeof zOut !== 'number') throw new Error('graphology-generators/random/girvan-newman: invalid `zOut`. Should be a number.'); if (typeof rng !== 'function') throw new Error('graphology-generators/random/girvan-newman: invalid `rng`. Should be a function.'); var pOut = zOut / 96, pIn = (16 - pOut * 96) / 31, graph = new GraphClass(), random, i, j; for (i = 0; i < 128; i++) graph.addNode(i); for (i = 0; i < 128; i++) { for (j = i + 1; j < 128; j++) { random = rng(); if (i % 4 === j % 4) { if (random < pIn) graph.addEdge(i, j); } else { if (random < pOut) graph.addEdge(i, j); } } } return graph; }; },{"graphology-utils/is-graph-constructor":107}],68:[function(require,module,exports){ /** * Graphology Random Graph Generators * =================================== * * Random graph generators endpoint. */ exports.clusters = require('./clusters.js'); exports.erdosRenyi = require('./erdos-renyi.js'); exports.girvanNewman = require('./girvan-newman.js'); },{"./clusters.js":65,"./erdos-renyi.js":66,"./girvan-newman.js":67}],69:[function(require,module,exports){ /** * Graphology Florentine Families Graph Generator * =============================================== * * Function generating the Florentine Families graph. * * [Reference]: * Ronald L. Breiger and Philippa E. Pattison * Cumulated social roles: The duality of persons and their algebras,1 * Social Networks, Volume 8, Issue 3, September 1986, Pages 215-256 */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'); /** * Data. */ var EDGES = [ ['Acciaiuoli', 'Medici'], ['Castellani', 'Peruzzi'], ['Castellani', 'Strozzi'], ['Castellani', 'Barbadori'], ['Medici', 'Barbadori'], ['Medici', 'Ridolfi'], ['Medici', 'Tornabuoni'], ['Medici', 'Albizzi'], ['Medici', 'Salviati'], ['Salviati', 'Pazzi'], ['Peruzzi', 'Strozzi'], ['Peruzzi', 'Bischeri'], ['Strozzi', 'Ridolfi'], ['Strozzi', 'Bischeri'], ['Ridolfi', 'Tornabuoni'], ['Tornabuoni', 'Guadagni'], ['Albizzi', 'Ginori'], ['Albizzi', 'Guadagni'], ['Bischeri', 'Guadagni'], ['Guadagni', 'Lamberteschi'] ]; /** * Function generating the florentine families graph. * * @param {Class} GraphClass - The Graph Class to instantiate. * @return {Graph} */ module.exports = function florentineFamilies(GraphClass) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/social/florentine-families: invalid Graph constructor.'); var graph = new GraphClass(), edge, i, l; for (i = 0, l = EDGES.length; i < l; i++) { edge = EDGES[i]; graph.mergeEdge(edge[0], edge[1]); } return graph; }; },{"graphology-utils/is-graph-constructor":107}],70:[function(require,module,exports){ /** * Graphology Social Graph Generators * =================================== * * Social graph generators endpoint. */ exports.florentineFamilies = require('./florentine-families.js'); exports.karateClub = require('./karate-club.js'); },{"./florentine-families.js":69,"./karate-club.js":71}],71:[function(require,module,exports){ /** * Graphology Karate Graph Generator * ================================== * * Function generating Zachary's karate club graph. * * [Reference]: * Zachary, Wayne W. * "An Information Flow Model for Conflict and Fission in Small Groups." * Journal of Anthropological Research, 33, 452--473, (1977). */ var isGraphConstructor = require('graphology-utils/is-graph-constructor'); /** * Data. */ var DATA = [ '0111111110111100010101000000000100', '1011000100000100010101000000001000', '1101000111000100000000000001100010', '1110000100001100000000000000000000', '1000001000100000000000000000000000', '1000001000100000100000000000000000', '1000110000000000100000000000000000', '1111000000000000000000000000000000', '1010000000000000000000000000001011', '0010000000000000000000000000000001', '1000110000000000000000000000000000', '1000000000000000000000000000000000', '1001000000000000000000000000000000', '1111000000000000000000000000000001', '0000000000000000000000000000000011', '0000000000000000000000000000000011', '0000011000000000000000000000000000', '1100000000000000000000000000000000', '0000000000000000000000000000000011', '1100000000000000000000000000000001', '0000000000000000000000000000000011', '1100000000000000000000000000000000', '0000000000000000000000000000000011', '0000000000000000000000000101010011', '0000000000000000000000000101000100', '0000000000000000000000011000000100', '0000000000000000000000000000010001', '0010000000000000000000011000000001', '0010000000000000000000000000000101', '0000000000000000000000010010000011', '0100000010000000000000000000000011', '1000000000000000000000001100100011', '0010000010000011001010110000011101', '0000000011000111001110110011111110' ]; var CLUB1 = new Set([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 16, 17, 19, 21 ]); /** * Function generating the karate club graph. * * @param {Class} GraphClass - The Graph Class to instantiate. * @return {Graph} */ module.exports = function karateClub(GraphClass) { if (!isGraphConstructor(GraphClass)) throw new Error('graphology-generators/social/karate: invalid Graph constructor.'); var graph = new GraphClass(), club; for (var i = 0; i < 34; i++) { club = CLUB1.has(i) ? 'Mr. Hi' : 'Officer'; graph.addNode(i, {club: club}); } var line, entry, row, column, l, m; for (row = 0, l = DATA.length; row < l; row++) { line = DATA[row].split(''); for (column = row + 1, m = line.length; column < m; column++) { entry = +line[column]; if (entry) graph.addEdgeWithKey(row + '->' + column, row, column); } } return graph; }; },{"graphology-utils/is-graph-constructor":107}],72:[function(require,module,exports){ /** * Graphology Outbound Neighborhood Indices * ========================================= */ var typed = require('mnemonist/utils/typed-arrays'); function OutboundNeighborhoodIndex(graph) { var upperBound = graph.directedSize + graph.undirectedSize * 2; var NeighborhoodPointerArray = typed.getPointerArray(upperBound); var NodesPointerArrray = typed.getPointerArray(graph.order); // NOTE: directedSize + undirectedSize * 2 is an upper bound for // neighborhood size this.graph = graph; this.neighborhood = new NodesPointerArrray(upperBound); this.starts = new NeighborhoodPointerArray(graph.order + 1); this.nodes = graph.nodes(); var ids = {}; var i, l, j, m, node, neighbors; var n = 0; for (i = 0, l = graph.order; i < l; i++) ids[this.nodes[i]] = i; for (i = 0, l = graph.order; i < l; i++) { node = this.nodes[i]; neighbors = graph.outboundNeighbors(node); this.starts[i] = n; for (j = 0, m = neighbors.length; j < m; j++) this.neighborhood[n++] = ids[neighbors[j]]; } // NOTE: we keep one more index as upper bound to simplify iteration this.starts[i] = upperBound; } OutboundNeighborhoodIndex.prototype.bounds = function(i) { return [this.starts[i], this.starts[i + 1]]; }; OutboundNeighborhoodIndex.prototype.project = function() { var self = this; var projection = {}; self.nodes.forEach(function(node, i) { projection[node] = Array.from( self.neighborhood.slice(self.starts[i], self.starts[i + 1]) ).map(function(j) { return self.nodes[j]; }); }); return projection; }; OutboundNeighborhoodIndex.prototype.collect = function(results) { var i, l; var o = {}; for (i = 0, l = results.length; i < l; i++) o[this.nodes[i]] = results[i]; return o; }; OutboundNeighborhoodIndex.prototype.assign = function(prop, results) { var i, l; for (i = 0, l = results.length; i < l; i++) this.graph.setNodeAttribute(this.nodes[i], prop, results[i]); }; exports.OutboundNeighborhoodIndex = OutboundNeighborhoodIndex; function WeightedOutboundNeighborhoodIndex(graph, weightAttribute) { var upperBound = graph.directedSize + graph.undirectedSize * 2; var NeighborhoodPointerArray = typed.getPointerArray(upperBound); var NodesPointerArrray = typed.getPointerArray(graph.order); weightAttribute = weightAttribute || 'weight'; // NOTE: directedSize + undirectedSize * 2 is an upper bound for // neighborhood size this.graph = graph; this.neighborhood = new NodesPointerArrray(upperBound); this.weights = new Float64Array(upperBound); this.starts = new NeighborhoodPointerArray(graph.order + 1); this.nodes = graph.nodes(); var ids = {}; var i, l, j, m, node, neighbor, edges, edge, weight; var n = 0; for (i = 0, l = graph.order; i < l; i++) ids[this.nodes[i]] = i; for (i = 0, l = graph.order; i < l; i++) { node = this.nodes[i]; edges = graph.outboundEdges(node); this.starts[i] = n; for (j = 0, m = edges.length; j < m; j++) { edge = edges[j]; neighbor = graph.opposite(node, edge); weight = graph.getEdgeAttribute(edge, weightAttribute); if (typeof weight !== 'number') weight = 1; // NOTE: for weighted mixed beware of merging weights if twice the same neighbor this.neighborhood[n] = ids[neighbor]; this.weights[n++] = weight; } } // NOTE: we keep one more index as upper bound to simplify iteration this.starts[i] = upperBound; } WeightedOutboundNeighborhoodIndex.prototype.bounds = OutboundNeighborhoodIndex.prototype.bounds; WeightedOutboundNeighborhoodIndex.prototype.project = OutboundNeighborhoodIndex.prototype.project; WeightedOutboundNeighborhoodIndex.prototype.collect = OutboundNeighborhoodIndex.prototype.collect; WeightedOutboundNeighborhoodIndex.prototype.assign = OutboundNeighborhoodIndex.prototype.assign; exports.WeightedOutboundNeighborhoodIndex = WeightedOutboundNeighborhoodIndex; },{"mnemonist/utils/typed-arrays":73}],73:[function(require,module,exports){ /** * Mnemonist Typed Array Helpers * ============================== * * Miscellaneous helpers related to typed arrays. */ /** * When using an unsigned integer array to store pointers, one might want to * choose the optimal word size in regards to the actual numbers of pointers * to store. * * This helpers does just that. * * @param {number} size - Expected size of the array to map. * @return {TypedArray} */ var MAX_8BIT_INTEGER = Math.pow(2, 8) - 1, MAX_16BIT_INTEGER = Math.pow(2, 16) - 1, MAX_32BIT_INTEGER = Math.pow(2, 32) - 1; var MAX_SIGNED_8BIT_INTEGER = Math.pow(2, 7) - 1, MAX_SIGNED_16BIT_INTEGER = Math.pow(2, 15) - 1, MAX_SIGNED_32BIT_INTEGER = Math.pow(2, 31) - 1; exports.getPointerArray = function(size) { var maxIndex = size - 1; if (maxIndex <= MAX_8BIT_INTEGER) return Uint8Array; if (maxIndex <= MAX_16BIT_INTEGER) return Uint16Array; if (maxIndex <= MAX_32BIT_INTEGER) return Uint32Array; return Float64Array; }; exports.getSignedPointerArray = function(size) { var maxIndex = size - 1; if (maxIndex <= MAX_SIGNED_8BIT_INTEGER) return Int8Array; if (maxIndex <= MAX_SIGNED_16BIT_INTEGER) return Int16Array; if (maxIndex <= MAX_SIGNED_32BIT_INTEGER) return Int32Array; return Float64Array; }; /** * Function returning the minimal type able to represent the given number. * * @param {number} value - Value to test. * @return {TypedArrayClass} */ exports.getNumberType = function(value) { // <= 32 bits itnteger? if (value === (value | 0)) { // Negative if (Math.sign(value) === -1) { if (value <= 127 && value >= -128) return Int8Array; if (value <= 32767 && value >= -32768) return Int16Array; return Int32Array; } else { if (value <= 255) return Uint8Array; if (value <= 65535) return Uint16Array; return Uint32Array; } } // 53 bits integer & floats // NOTE: it's kinda hard to tell whether we could use 32bits or not... return Float64Array; }; /** * Function returning the minimal type able to represent the given array * of JavaScript numbers. * * @param {array} array - Array to represent. * @param {function} getter - Optional getter. * @return {TypedArrayClass} */ var TYPE_PRIORITY = { Uint8Array: 1, Int8Array: 2, Uint16Array: 3, Int16Array: 4, Uint32Array: 5, Int32Array: 6, Float32Array: 7, Float64Array: 8 }; // TODO: make this a one-shot for one value exports.getMinimalRepresentation = function(array, getter) { var maxType = null, maxPriority = 0, p, t, v, i, l; for (i = 0, l = array.length; i < l; i++) { v = getter ? getter(array[i]) : array[i]; t = exports.getNumberType(v); p = TYPE_PRIORITY[t.name]; if (p > maxPriority) { maxPriority = p; maxType = t; } } return maxType; }; /** * Function returning whether the given value is a typed array. * * @param {any} value - Value to test. * @return {boolean} */ exports.isTypedArray = function(value) { return typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(value); }; /** * Function used to concat byte arrays. * * @param {...ByteArray} * @return {ByteArray} */ exports.concat = function() { var length = 0, i, o, l; for (i = 0, l = arguments.length; i < l; i++) length += arguments[i].length; var array = new (arguments[0].constructor)(length); for (i = 0, o = 0; i < l; i++) { array.set(arguments[i], o); o += arguments[i].length; } return array; }; /** * Function used to initialize a byte array of indices. * * @param {number} length - Length of target. * @return {ByteArray} */ exports.indices = function(length) { var PointerArray = exports.getPointerArray(length); var array = new PointerArray(length); for (var i = 0; i < length; i++) array[i] = i; return array; }; },{}],74:[function(require,module,exports){ /** * Graphology ForceAtlas2 Layout Default Settings * =============================================== */ module.exports = { linLogMode: false, outboundAttractionDistribution: false, adjustSizes: false, edgeWeightInfluence: 0, scalingRatio: 1, strongGravityMode: false, gravity: 1, slowDown: 1, barnesHutOptimize: false, barnesHutTheta: 0.5 }; },{}],75:[function(require,module,exports){ /** * Graphology ForceAtlas2 Helpers * =============================== * * Miscellaneous helper functions. */ /** * Constants. */ var PPN = 10, PPE = 3; /** * Very simple Object.assign-like function. * * @param {object} target - First object. * @param {object} [...objects] - Objects to merge. * @return {object} */ exports.assign = function(target) { target = target || {}; var objects = Array.prototype.slice.call(arguments).slice(1), i, k, l; for (i = 0, l = objects.length; i < l; i++) { if (!objects[i]) continue; for (k in objects[i]) target[k] = objects[i][k]; } return target; }; /** * Function used to validate the given settings. * * @param {object} settings - Settings to validate. * @return {object|null} */ exports.validateSettings = function(settings) { if ('linLogMode' in settings && typeof settings.linLogMode !== 'boolean') return {message: 'the `linLogMode` setting should be a boolean.'}; if ('outboundAttractionDistribution' in settings && typeof settings.outboundAttractionDistribution !== 'boolean') return {message: 'the `outboundAttractionDistribution` setting should be a boolean.'}; if ('adjustSizes' in settings && typeof settings.adjustSizes !== 'boolean') return {message: 'the `adjustSizes` setting should be a boolean.'}; if ('edgeWeightInfluence' in settings && typeof settings.edgeWeightInfluence !== 'number' && settings.edgeWeightInfluence < 0) return {message: 'the `edgeWeightInfluence` setting should be a number >= 0.'}; if ('scalingRatio' in settings && typeof settings.scalingRatio !== 'number' && settings.scalingRatio < 0) return {message: 'the `scalingRatio` setting should be a number >= 0.'}; if ('strongGravityMode' in settings && typeof settings.strongGravityMode !== 'boolean') return {message: 'the `strongGravityMode` setting should be a boolean.'}; if ('gravity' in settings && typeof settings.gravity !== 'number' && settings.gravity < 0) return {message: 'the `gravity` setting should be a number >= 0.'}; if ('slowDown' in settings && typeof settings.slowDown !== 'number' && settings.slowDown < 0) return {message: 'the `slowDown` setting should be a number >= 0.'}; if ('barnesHutOptimize' in settings && typeof settings.barnesHutOptimize !== 'boolean') return {message: 'the `barnesHutOptimize` setting should be a boolean.'}; if ('barnesHutTheta' in settings && typeof settings.barnesHutTheta !== 'number' && settings.barnesHutTheta < 0) return {message: 'the `barnesHutTheta` setting should be a number >= 0.'}; return null; }; /** * Function generating a flat matrix for both nodes & edges of the given graph. * * @param {Graph} graph - Target graph. * @return {object} - Both matrices. */ exports.graphToByteArrays = function(graph) { var nodes = graph.nodes(), edges = graph.edges(), order = nodes.length, size = edges.length, index = {}, i, j; var NodeMatrix = new Float32Array(order * PPN), EdgeMatrix = new Float32Array(size * PPE); // Iterate through nodes for (i = j = 0; i < order; i++) { // Node index index[nodes[i]] = j; // Populating byte array NodeMatrix[j] = graph.getNodeAttribute(nodes[i], 'x'); NodeMatrix[j + 1] = graph.getNodeAttribute(nodes[i], 'y'); NodeMatrix[j + 2] = 0; NodeMatrix[j + 3] = 0; NodeMatrix[j + 4] = 0; NodeMatrix[j + 5] = 0; NodeMatrix[j + 6] = 1 + graph.degree(nodes[i]); NodeMatrix[j + 7] = 1; NodeMatrix[j + 8] = graph.getNodeAttribute(nodes[i], 'size') || 1; NodeMatrix[j + 9] = 0; j += PPN; } // Iterate through edges for (i = j = 0; i < size; i++) { // Populating byte array EdgeMatrix[j] = index[graph.source(edges[i])]; EdgeMatrix[j + 1] = index[graph.target(edges[i])]; EdgeMatrix[j + 2] = graph.getEdgeAttribute(edges[i], 'weight') || 0; j += PPE; } return { nodes: NodeMatrix, edges: EdgeMatrix }; }; /** * Function applying the layout back to the graph. * * @param {Graph} graph - Target graph. * @param {Float32Array} NodeMatrix - Node matrix. */ exports.assignLayoutChanges = function(graph, NodeMatrix) { var nodes = graph.nodes(); for (var i = 0, j = 0, l = NodeMatrix.length; i < l; i += PPN) { graph.setNodeAttribute(nodes[j], 'x', NodeMatrix[i]); graph.setNodeAttribute(nodes[j], 'y', NodeMatrix[i + 1]); j++; } }; /** * Function collecting the layout positions. * * @param {Graph} graph - Target graph. * @param {Float32Array} NodeMatrix - Node matrix. * @return {object} - Map to node positions. */ exports.collectLayoutChanges = function(graph, NodeMatrix) { var nodes = graph.nodes(), positions = Object.create(null); for (var i = 0, j = 0, l = NodeMatrix.length; i < l; i += PPN) { positions[nodes[j]] = { x: NodeMatrix[i], y: NodeMatrix[i + 1] }; j++; } return positions; }; },{}],76:[function(require,module,exports){ /** * Graphology ForceAtlas2 Layout * ============================== * * Library endpoint. */ var isGraph = require('graphology-utils/is-graph'), iterate = require('./iterate.js'), helpers = require('./helpers.js'); var DEFAULT_SETTINGS = require('./defaults.js'); /** * Asbtract function used to run a certain number of iterations. * * @param {boolean} assign - Whether to assign positions. * @param {Graph} graph - Target graph. * @param {object|number} params - If number, params.iterations, else: * @param {number} iterations - Number of iterations. * @param {object} [settings] - Settings. * @return {object|undefined} */ function abstractSynchronousLayout(assign, graph, params) { if (!isGraph(graph)) throw new Error('graphology-layout-forceatlas2: the given graph is not a valid graphology instance.'); if (typeof params === 'number') params = {iterations: params}; var iterations = params.iterations; if (typeof iterations !== 'number') throw new Error('graphology-layout-forceatlas2: invalid number of iterations.'); if (iterations <= 0) throw new Error('graphology-layout-forceatlas2: you should provide a positive number of iterations.'); // Validating settings var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings), validationError = helpers.validateSettings(settings); if (validationError) throw new Error('graphology-layout-forceatlas2: ' + validationError.message); // Building matrices var matrices = helpers.graphToByteArrays(graph), i; // Iterating for (i = 0; i < iterations; i++) iterate(settings, matrices.nodes, matrices.edges); // Applying if (assign) { helpers.assignLayoutChanges(graph, matrices.nodes); return; } return helpers.collectLayoutChanges(graph, matrices.nodes); } /** * Function returning sane layout settings for the given graph. * * @param {Graph} graph - Target graph. * @return {object} */ function inferSettings(graph) { var order = graph.order; return { barnesHutOptimize: order > 2000, strongGravityMode: true, gravity: 0.05, scalingRatio: 10, slowDown: 1 + Math.log(order) }; } /** * Exporting. */ var synchronousLayout = abstractSynchronousLayout.bind(null, false); synchronousLayout.assign = abstractSynchronousLayout.bind(null, true); synchronousLayout.inferSettings = inferSettings; module.exports = synchronousLayout; },{"./defaults.js":74,"./helpers.js":75,"./iterate.js":77,"graphology-utils/is-graph":108}],77:[function(require,module,exports){ /* eslint no-constant-condition: 0 */ /** * Graphology ForceAtlas2 Iteration * ================================= * * Function used to perform a single iteration of the algorithm. */ /** * Matrices properties accessors. */ var NODE_X = 0, NODE_Y = 1, NODE_DX = 2, NODE_DY = 3, NODE_OLD_DX = 4, NODE_OLD_DY = 5, NODE_MASS = 6, NODE_CONVERGENCE = 7, NODE_SIZE = 8, NODE_FIXED = 9; var EDGE_SOURCE = 0, EDGE_TARGET = 1, EDGE_WEIGHT = 2; var REGION_NODE = 0, REGION_CENTER_X = 1, REGION_CENTER_Y = 2, REGION_SIZE = 3, REGION_NEXT_SIBLING = 4, REGION_FIRST_CHILD = 5, REGION_MASS = 6, REGION_MASS_CENTER_X = 7, REGION_MASS_CENTER_Y = 8; var SUBDIVISION_ATTEMPTS = 3; /** * Constants. */ var PPN = 10, PPE = 3, PPR = 9; var MAX_FORCE = 10; /** * Function used to perform a single interation of the algorithm. * * @param {object} options - Layout options. * @param {Float32Array} NodeMatrix - Node data. * @param {Float32Array} EdgeMatrix - Edge data. * @return {object} - Some metadata. */ module.exports = function iterate(options, NodeMatrix, EdgeMatrix) { // Initializing variables var l, r, n, n1, n2, rn, e, w, g, s; var order = NodeMatrix.length, size = EdgeMatrix.length; var adjustSizes = options.adjustSizes; var thetaSquared = options.barnesHutTheta * options.barnesHutTheta; var outboundAttCompensation, coefficient, xDist, yDist, ewc, distance, factor; var RegionMatrix = []; // 1) Initializing layout data //----------------------------- // Resetting positions & computing max values for (n = 0; n < order; n += PPN) { NodeMatrix[n + NODE_OLD_DX] = NodeMatrix[n + NODE_DX]; NodeMatrix[n + NODE_OLD_DY] = NodeMatrix[n + NODE_DY]; NodeMatrix[n + NODE_DX] = 0; NodeMatrix[n + NODE_DY] = 0; } // If outbound attraction distribution, compensate if (options.outboundAttractionDistribution) { outboundAttCompensation = 0; for (n = 0; n < order; n += PPN) { outboundAttCompensation += NodeMatrix[n + NODE_MASS]; } outboundAttCompensation /= (order / PPN); } // 1.bis) Barnes-Hut computation //------------------------------ if (options.barnesHutOptimize) { // Setting up var minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity, q, q2, subdivisionAttempts; // Computing min and max values for (n = 0; n < order; n += PPN) { minX = Math.min(minX, NodeMatrix[n + NODE_X]); maxX = Math.max(maxX, NodeMatrix[n + NODE_X]); minY = Math.min(minY, NodeMatrix[n + NODE_Y]); maxY = Math.max(maxY, NodeMatrix[n + NODE_Y]); } // squarify bounds, it's a quadtree var dx = maxX - minX, dy = maxY - minY; if (dx > dy) { minY -= (dx - dy) / 2; maxY = minY + dx; } else { minX -= (dy - dx) / 2; maxX = minX + dy; } // Build the Barnes Hut root region RegionMatrix[0 + REGION_NODE] = -1; RegionMatrix[0 + REGION_CENTER_X] = (minX + maxX) / 2; RegionMatrix[0 + REGION_CENTER_Y] = (minY + maxY) / 2; RegionMatrix[0 + REGION_SIZE] = Math.max(maxX - minX, maxY - minY); RegionMatrix[0 + REGION_NEXT_SIBLING] = -1; RegionMatrix[0 + REGION_FIRST_CHILD] = -1; RegionMatrix[0 + REGION_MASS] = 0; RegionMatrix[0 + REGION_MASS_CENTER_X] = 0; RegionMatrix[0 + REGION_MASS_CENTER_Y] = 0; // Add each node in the tree l = 1; for (n = 0; n < order; n += PPN) { // Current region, starting with root r = 0; subdivisionAttempts = SUBDIVISION_ATTEMPTS; while (true) { // Are there sub-regions? // We look at first child index if (RegionMatrix[r + REGION_FIRST_CHILD] >= 0) { // There are sub-regions // We just iterate to find a "leaf" of the tree // that is an empty region or a region with a single node // (see next case) // Find the quadrant of n if (NodeMatrix[n + NODE_X] < RegionMatrix[r + REGION_CENTER_X]) { if (NodeMatrix[n + NODE_Y] < RegionMatrix[r + REGION_CENTER_Y]) { // Top Left quarter q = RegionMatrix[r + REGION_FIRST_CHILD]; } else { // Bottom Left quarter q = RegionMatrix[r + REGION_FIRST_CHILD] + PPR; } } else { if (NodeMatrix[n + NODE_Y] < RegionMatrix[r + REGION_CENTER_Y]) { // Top Right quarter q = RegionMatrix[r + REGION_FIRST_CHILD] + PPR * 2; } else { // Bottom Right quarter q = RegionMatrix[r + REGION_FIRST_CHILD] + PPR * 3; } } // Update center of mass and mass (we only do it for non-leave regions) RegionMatrix[r + REGION_MASS_CENTER_X] = (RegionMatrix[r + REGION_MASS_CENTER_X] * RegionMatrix[r + REGION_MASS] + NodeMatrix[n + NODE_X] * NodeMatrix[n + NODE_MASS]) / (RegionMatrix[r + REGION_MASS] + NodeMatrix[n + NODE_MASS]); RegionMatrix[r + REGION_MASS_CENTER_Y] = (RegionMatrix[r + REGION_MASS_CENTER_Y] * RegionMatrix[r + REGION_MASS] + NodeMatrix[n + NODE_Y] * NodeMatrix[n + NODE_MASS]) / (RegionMatrix[r + REGION_MASS] + NodeMatrix[n + NODE_MASS]); RegionMatrix[r + REGION_MASS] += NodeMatrix[n + NODE_MASS]; // Iterate on the right quadrant r = q; continue; } else { // There are no sub-regions: we are in a "leaf" // Is there a node in this leave? if (RegionMatrix[r + REGION_NODE] < 0) { // There is no node in region: // we record node n and go on RegionMatrix[r + REGION_NODE] = n; break; } else { // There is a node in this region // We will need to create sub-regions, stick the two // nodes (the old one r[0] and the new one n) in two // subregions. If they fall in the same quadrant, // we will iterate. // Create sub-regions RegionMatrix[r + REGION_FIRST_CHILD] = l * PPR; w = RegionMatrix[r + REGION_SIZE] / 2; // new size (half) // NOTE: we use screen coordinates // from Top Left to Bottom Right // Top Left sub-region g = RegionMatrix[r + REGION_FIRST_CHILD]; RegionMatrix[g + REGION_NODE] = -1; RegionMatrix[g + REGION_CENTER_X] = RegionMatrix[r + REGION_CENTER_X] - w; RegionMatrix[g + REGION_CENTER_Y] = RegionMatrix[r + REGION_CENTER_Y] - w; RegionMatrix[g + REGION_SIZE] = w; RegionMatrix[g + REGION_NEXT_SIBLING] = g + PPR; RegionMatrix[g + REGION_FIRST_CHILD] = -1; RegionMatrix[g + REGION_MASS] = 0; RegionMatrix[g + REGION_MASS_CENTER_X] = 0; RegionMatrix[g + REGION_MASS_CENTER_Y] = 0; // Bottom Left sub-region g += PPR; RegionMatrix[g + REGION_NODE] = -1; RegionMatrix[g + REGION_CENTER_X] = RegionMatrix[r + REGION_CENTER_X] - w; RegionMatrix[g + REGION_CENTER_Y] = RegionMatrix[r + REGION_CENTER_Y] + w; RegionMatrix[g + REGION_SIZE] = w; RegionMatrix[g + REGION_NEXT_SIBLING] = g + PPR; RegionMatrix[g + REGION_FIRST_CHILD] = -1; RegionMatrix[g + REGION_MASS] = 0; RegionMatrix[g + REGION_MASS_CENTER_X] = 0; RegionMatrix[g + REGION_MASS_CENTER_Y] = 0; // Top Right sub-region g += PPR; RegionMatrix[g + REGION_NODE] = -1; RegionMatrix[g + REGION_CENTER_X] = RegionMatrix[r + REGION_CENTER_X] + w; RegionMatrix[g + REGION_CENTER_Y] = RegionMatrix[r + REGION_CENTER_Y] - w; RegionMatrix[g + REGION_SIZE] = w; RegionMatrix[g + REGION_NEXT_SIBLING] = g + PPR; RegionMatrix[g + REGION_FIRST_CHILD] = -1; RegionMatrix[g + REGION_MASS] = 0; RegionMatrix[g + REGION_MASS_CENTER_X] = 0; RegionMatrix[g + REGION_MASS_CENTER_Y] = 0; // Bottom Right sub-region g += PPR; RegionMatrix[g + REGION_NODE] = -1; RegionMatrix[g + REGION_CENTER_X] = RegionMatrix[r + REGION_CENTER_X] + w; RegionMatrix[g + REGION_CENTER_Y] = RegionMatrix[r + REGION_CENTER_Y] + w; RegionMatrix[g + REGION_SIZE] = w; RegionMatrix[g + REGION_NEXT_SIBLING] = RegionMatrix[r + REGION_NEXT_SIBLING]; RegionMatrix[g + REGION_FIRST_CHILD] = -1; RegionMatrix[g + REGION_MASS] = 0; RegionMatrix[g + REGION_MASS_CENTER_X] = 0; RegionMatrix[g + REGION_MASS_CENTER_Y] = 0; l += 4; // Now the goal is to find two different sub-regions // for the two nodes: the one previously recorded (r[0]) // and the one we want to add (n) // Find the quadrant of the old node if (NodeMatrix[RegionMatrix[r + REGION_NODE] + NODE_X] < RegionMatrix[r + REGION_CENTER_X]) { if (NodeMatrix[RegionMatrix[r + REGION_NODE] + NODE_Y] < RegionMatrix[r + REGION_CENTER_Y]) { // Top Left quarter q = RegionMatrix[r + REGION_FIRST_CHILD]; } else { // Bottom Left quarter q = RegionMatrix[r + REGION_FIRST_CHILD] + PPR; } } else { if (NodeMatrix[RegionMatrix[r + REGION_NODE] + NODE_Y] < RegionMatrix[r + REGION_CENTER_Y]) { // Top Right quarter q = RegionMatrix[r + REGION_FIRST_CHILD] + PPR * 2; } else { // Bottom Right quarter q = RegionMatrix[r + REGION_FIRST_CHILD] + PPR * 3; } } // We remove r[0] from the region r, add its mass to r and record it in q RegionMatrix[r + REGION_MASS] = NodeMatrix[RegionMatrix[r + REGION_NODE] + NODE_MASS]; RegionMatrix[r + REGION_MASS_CENTER_X] = NodeMatrix[RegionMatrix[r + REGION_NODE] + NODE_X]; RegionMatrix[r + REGION_MASS_CENTER_Y] = NodeMatrix[RegionMatrix[r + REGION_NODE] + NODE_Y]; RegionMatrix[q + REGION_NODE] = RegionMatrix[r + REGION_NODE]; RegionMatrix[r + REGION_NODE] = -1; // Find the quadrant of n if (NodeMatrix[n + NODE_X] < RegionMatrix[r + REGION_CENTER_X]) { if (NodeMatrix[n + NODE_Y] < RegionMatrix[r + REGION_CENTER_Y]) { // Top Left quarter q2 = RegionMatrix[r + REGION_FIRST_CHILD]; } else { // Bottom Left quarter q2 = RegionMatrix[r + REGION_FIRST_CHILD] + PPR; } } else { if (NodeMatrix[n + NODE_Y] < RegionMatrix[r + REGION_CENTER_Y]) { // Top Right quarter q2 = RegionMatrix[r + REGION_FIRST_CHILD] + PPR * 2; } else { // Bottom Right quarter q2 = RegionMatrix[r + REGION_FIRST_CHILD] + PPR * 3; } } if (q === q2) { // If both nodes are in the same quadrant, // we have to try it again on this quadrant if (subdivisionAttempts--) { r = q; continue; // while } else { // we are out of precision here, and we cannot subdivide anymore // but we have to break the loop anyway subdivisionAttempts = SUBDIVISION_ATTEMPTS; break; // while } } // If both quadrants are different, we record n // in its quadrant RegionMatrix[q2 + REGION_NODE] = n; break; } } } } } // 2) Repulsion //-------------- // NOTES: adjustSizes = antiCollision & scalingRatio = coefficient if (options.barnesHutOptimize) { coefficient = options.scalingRatio; // Applying repulsion through regions for (n = 0; n < order; n += PPN) { // Computing leaf quad nodes iteration r = 0; // Starting with root region while (true) { if (RegionMatrix[r + REGION_FIRST_CHILD] >= 0) { // The region has sub-regions // We run the Barnes Hut test to see if we are at the right distance distance = ( (Math.pow(NodeMatrix[n + NODE_X] - RegionMatrix[r + REGION_MASS_CENTER_X], 2)) + (Math.pow(NodeMatrix[n + NODE_Y] - RegionMatrix[r + REGION_MASS_CENTER_Y], 2)) ); s = RegionMatrix[r + REGION_SIZE]; if ((4 * s * s) / distance < thetaSquared) { // We treat the region as a single body, and we repulse xDist = NodeMatrix[n + NODE_X] - RegionMatrix[r + REGION_MASS_CENTER_X]; yDist = NodeMatrix[n + NODE_Y] - RegionMatrix[r + REGION_MASS_CENTER_Y]; if (adjustSizes === true) { //-- Linear Anti-collision Repulsion if (distance > 0) { factor = coefficient * NodeMatrix[n + NODE_MASS] * RegionMatrix[r + REGION_MASS] / distance; NodeMatrix[n + NODE_DX] += xDist * factor; NodeMatrix[n + NODE_DY] += yDist * factor; } else if (distance < 0) { factor = -coefficient * NodeMatrix[n + NODE_MASS] * RegionMatrix[r + REGION_MASS] / Math.sqrt(distance); NodeMatrix[n + NODE_DX] += xDist * factor; NodeMatrix[n + NODE_DY] += yDist * factor; } } else { //-- Linear Repulsion if (distance > 0) { factor = coefficient * NodeMatrix[n + NODE_MASS] * RegionMatrix[r + REGION_MASS] / distance; NodeMatrix[n + NODE_DX] += xDist * factor; NodeMatrix[n + NODE_DY] += yDist * factor; } } // When this is done, we iterate. We have to look at the next sibling. r = RegionMatrix[r + REGION_NEXT_SIBLING]; if (r < 0) break; // No next sibling: we have finished the tree continue; } else { // The region is too close and we have to look at sub-regions r = RegionMatrix[r + REGION_FIRST_CHILD]; continue; } } else { // The region has no sub-region // If there is a node r[0] and it is not n, then repulse rn = RegionMatrix[r + REGION_NODE]; if (rn >= 0 && rn !== n) { xDist = NodeMatrix[n + NODE_X] - NodeMatrix[rn + NODE_X]; yDist = NodeMatrix[n + NODE_Y] - NodeMatrix[rn + NODE_Y]; distance = xDist * xDist + yDist * yDist; if (adjustSizes === true) { //-- Linear Anti-collision Repulsion if (distance > 0) { factor = coefficient * NodeMatrix[n + NODE_MASS] * NodeMatrix[rn + NODE_MASS] / distance; NodeMatrix[n + NODE_DX] += xDist * factor; NodeMatrix[n + NODE_DY] += yDist * factor; } else if (distance < 0) { factor = -coefficient * NodeMatrix[n + NODE_MASS] * NodeMatrix[rn + NODE_MASS] / Math.sqrt(distance); NodeMatrix[n + NODE_DX] += xDist * factor; NodeMatrix[n + NODE_DY] += yDist * factor; } } else { //-- Linear Repulsion if (distance > 0) { factor = coefficient * NodeMatrix[n + NODE_MASS] * NodeMatrix[rn + NODE_MASS] / distance; NodeMatrix[n + NODE_DX] += xDist * factor; NodeMatrix[n + NODE_DY] += yDist * factor; } } } // When this is done, we iterate. We have to look at the next sibling. r = RegionMatrix[r + REGION_NEXT_SIBLING]; if (r < 0) break; // No next sibling: we have finished the tree continue; } } } } else { coefficient = options.scalingRatio; // Square iteration for (n1 = 0; n1 < order; n1 += PPN) { for (n2 = 0; n2 < n1; n2 += PPN) { // Common to both methods xDist = NodeMatrix[n1 + NODE_X] - NodeMatrix[n2 + NODE_X]; yDist = NodeMatrix[n1 + NODE_Y] - NodeMatrix[n2 + NODE_Y]; if (adjustSizes === true) { //-- Anticollision Linear Repulsion distance = Math.sqrt(xDist * xDist + yDist * yDist) - NodeMatrix[n1 + NODE_SIZE] - NodeMatrix[n2 + NODE_SIZE]; if (distance > 0) { factor = coefficient * NodeMatrix[n1 + NODE_MASS] * NodeMatrix[n2 + NODE_MASS] / distance / distance; // Updating nodes' dx and dy NodeMatrix[n1 + NODE_DX] += xDist * factor; NodeMatrix[n1 + NODE_DY] += yDist * factor; NodeMatrix[n2 + NODE_DX] += xDist * factor; NodeMatrix[n2 + NODE_DY] += yDist * factor; } else if (distance < 0) { factor = 100 * coefficient * NodeMatrix[n1 + NODE_MASS] * NodeMatrix[n2 + NODE_MASS]; // Updating nodes' dx and dy NodeMatrix[n1 + NODE_DX] += xDist * factor; NodeMatrix[n1 + NODE_DY] += yDist * factor; NodeMatrix[n2 + NODE_DX] -= xDist * factor; NodeMatrix[n2 + NODE_DY] -= yDist * factor; } } else { //-- Linear Repulsion distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { factor = coefficient * NodeMatrix[n1 + NODE_MASS] * NodeMatrix[n2 + NODE_MASS] / distance / distance; // Updating nodes' dx and dy NodeMatrix[n1 + NODE_DX] += xDist * factor; NodeMatrix[n1 + NODE_DY] += yDist * factor; NodeMatrix[n2 + NODE_DX] -= xDist * factor; NodeMatrix[n2 + NODE_DY] -= yDist * factor; } } } } } // 3) Gravity //------------ g = options.gravity / options.scalingRatio; coefficient = options.scalingRatio; for (n = 0; n < order; n += PPN) { factor = 0; // Common to both methods xDist = NodeMatrix[n + NODE_X]; yDist = NodeMatrix[n + NODE_Y]; distance = Math.sqrt( Math.pow(xDist, 2) + Math.pow(yDist, 2) ); if (options.strongGravityMode) { //-- Strong gravity if (distance > 0) factor = coefficient * NodeMatrix[n + NODE_MASS] * g; } else { //-- Linear Anti-collision Repulsion n if (distance > 0) factor = coefficient * NodeMatrix[n + NODE_MASS] * g / distance; } // Updating node's dx and dy NodeMatrix[n + NODE_DX] -= xDist * factor; NodeMatrix[n + NODE_DY] -= yDist * factor; } // 4) Attraction //--------------- coefficient = 1 * (options.outboundAttractionDistribution ? outboundAttCompensation : 1); // TODO: simplify distance // TODO: coefficient is always used as -c --> optimize? for (e = 0; e < size; e += PPE) { n1 = EdgeMatrix[e + EDGE_SOURCE]; n2 = EdgeMatrix[e + EDGE_TARGET]; w = EdgeMatrix[e + EDGE_WEIGHT]; // Edge weight influence ewc = Math.pow(w, options.edgeWeightInfluence); // Common measures xDist = NodeMatrix[n1 + NODE_X] - NodeMatrix[n2 + NODE_X]; yDist = NodeMatrix[n1 + NODE_Y] - NodeMatrix[n2 + NODE_Y]; // Applying attraction to nodes if (adjustSizes === true) { distance = Math.sqrt( (Math.pow(xDist, 2) + Math.pow(yDist, 2)) - NodeMatrix[n1 + NODE_SIZE] - NodeMatrix[n2 + NODE_SIZE] ); if (options.linLogMode) { if (options.outboundAttractionDistribution) { //-- LinLog Degree Distributed Anti-collision Attraction if (distance > 0) { factor = -coefficient * ewc * Math.log(1 + distance) / distance / NodeMatrix[n1 + NODE_MASS]; } } else { //-- LinLog Anti-collision Attraction if (distance > 0) { factor = -coefficient * ewc * Math.log(1 + distance) / distance; } } } else { if (options.outboundAttractionDistribution) { //-- Linear Degree Distributed Anti-collision Attraction if (distance > 0) { factor = -coefficient * ewc / NodeMatrix[n1 + NODE_MASS]; } } else { //-- Linear Anti-collision Attraction if (distance > 0) { factor = -coefficient * ewc; } } } } else { distance = Math.sqrt( Math.pow(xDist, 2) + Math.pow(yDist, 2) ); if (options.linLogMode) { if (options.outboundAttractionDistribution) { //-- LinLog Degree Distributed Attraction if (distance > 0) { factor = -coefficient * ewc * Math.log(1 + distance) / distance / NodeMatrix[n1 + NODE_MASS]; } } else { //-- LinLog Attraction if (distance > 0) factor = -coefficient * ewc * Math.log(1 + distance) / distance; } } else { if (options.outboundAttractionDistribution) { //-- Linear Attraction Mass Distributed // NOTE: Distance is set to 1 to override next condition distance = 1; factor = -coefficient * ewc / NodeMatrix[n1 + NODE_MASS]; } else { //-- Linear Attraction // NOTE: Distance is set to 1 to override next condition distance = 1; factor = -coefficient * ewc; } } } // Updating nodes' dx and dy // TODO: if condition or factor = 1? if (distance > 0) { // Updating nodes' dx and dy NodeMatrix[n1 + NODE_DX] += xDist * factor; NodeMatrix[n1 + NODE_DY] += yDist * factor; NodeMatrix[n2 + NODE_DX] -= xDist * factor; NodeMatrix[n2 + NODE_DY] -= yDist * factor; } } // 5) Apply Forces //----------------- var force, swinging, traction, nodespeed, newX, newY; // MATH: sqrt and square distances if (adjustSizes === true) { for (n = 0; n < order; n += PPN) { if (!NodeMatrix[n + NODE_FIXED]) { force = Math.sqrt( Math.pow(NodeMatrix[n + NODE_DX], 2) + Math.pow(NodeMatrix[n + NODE_DY], 2) ); if (force > MAX_FORCE) { NodeMatrix[n + NODE_DX] = NodeMatrix[n + NODE_DX] * MAX_FORCE / force; NodeMatrix[n + NODE_DY] = NodeMatrix[n + NODE_DY] * MAX_FORCE / force; } swinging = NodeMatrix[n + NODE_MASS] * Math.sqrt( (NodeMatrix[n + NODE_OLD_DX] - NodeMatrix[n + NODE_DX]) * (NodeMatrix[n + NODE_OLD_DX] - NodeMatrix[n + NODE_DX]) + (NodeMatrix[n + NODE_OLD_DY] - NodeMatrix[n + NODE_DY]) * (NodeMatrix[n + NODE_OLD_DY] - NodeMatrix[n + NODE_DY]) ); traction = Math.sqrt( (NodeMatrix[n + NODE_OLD_DX] + NodeMatrix[n + NODE_DX]) * (NodeMatrix[n + NODE_OLD_DX] + NodeMatrix[n + NODE_DX]) + (NodeMatrix[n + NODE_OLD_DY] + NodeMatrix[n + NODE_DY]) * (NodeMatrix[n + NODE_OLD_DY] + NodeMatrix[n + NODE_DY]) ) / 2; nodespeed = 0.1 * Math.log(1 + traction) / (1 + Math.sqrt(swinging)); // Updating node's positon newX = NodeMatrix[n + NODE_X] + NodeMatrix[n + NODE_DX] * (nodespeed / options.slowDown); NodeMatrix[n + NODE_X] = newX; newY = NodeMatrix[n + NODE_Y] + NodeMatrix[n + NODE_DY] * (nodespeed / options.slowDown); NodeMatrix[n + NODE_Y] = newY; } } } else { for (n = 0; n < order; n += PPN) { if (!NodeMatrix[n + NODE_FIXED]) { swinging = NodeMatrix[n + NODE_MASS] * Math.sqrt( (NodeMatrix[n + NODE_OLD_DX] - NodeMatrix[n + NODE_DX]) * (NodeMatrix[n + NODE_OLD_DX] - NodeMatrix[n + NODE_DX]) + (NodeMatrix[n + NODE_OLD_DY] - NodeMatrix[n + NODE_DY]) * (NodeMatrix[n + NODE_OLD_DY] - NodeMatrix[n + NODE_DY]) ); traction = Math.sqrt( (NodeMatrix[n + NODE_OLD_DX] + NodeMatrix[n + NODE_DX]) * (NodeMatrix[n + NODE_OLD_DX] + NodeMatrix[n + NODE_DX]) + (NodeMatrix[n + NODE_OLD_DY] + NodeMatrix[n + NODE_DY]) * (NodeMatrix[n + NODE_OLD_DY] + NodeMatrix[n + NODE_DY]) ) / 2; nodespeed = NodeMatrix[n + NODE_CONVERGENCE] * Math.log(1 + traction) / (1 + Math.sqrt(swinging)); // Updating node convergence NodeMatrix[n + NODE_CONVERGENCE] = Math.min(1, Math.sqrt( nodespeed * (Math.pow(NodeMatrix[n + NODE_DX], 2) + Math.pow(NodeMatrix[n + NODE_DY], 2)) / (1 + Math.sqrt(swinging)) )); // Updating node's positon newX = NodeMatrix[n + NODE_X] + NodeMatrix[n + NODE_DX] * (nodespeed / options.slowDown); NodeMatrix[n + NODE_X] = newX; newY = NodeMatrix[n + NODE_Y] + NodeMatrix[n + NODE_DY] * (nodespeed / options.slowDown); NodeMatrix[n + NODE_Y] = newY; } } } // We return the information about the layout (no need to return the matrices) return {}; }; },{}],78:[function(require,module,exports){ /** * Graphology Circular Layout * =========================== * * Layout arranging the nodes in a circle. */ var defaults = require('lodash/defaultsDeep'), isGraph = require('graphology-utils/is-graph'); /** * Default options. */ var DEFAULTS = { attributes: { x: 'x', y: 'y' }, center: 0.5, scale: 1 }; /** * Abstract function running the layout. * * @param {Graph} graph - Target graph. * @param {object} [options] - Options: * @param {object} [attributes] - Attributes names to map. * @param {number} [center] - Center of the layout. * @param {number} [scale] - Scale of the layout. * @return {object} - The positions by node. */ function genericCircularLayout(assign, graph, options) { if (!isGraph(graph)) throw new Error('graphology-layout/random: the given graph is not a valid graphology instance.'); options = defaults(options, DEFAULTS); var positions = {}, nodes = graph.nodes(), center = options.center, scale = options.scale, tau = Math.PI * 2; var l = nodes.length, node, x, y, i; for (i = 0; i < l; i++) { node = nodes[i]; x = scale * Math.cos(i * tau / l); y = scale * Math.sin(i * tau / l); if (center !== 0.5) { x += center - 0.5 * scale; y += center - 0.5 * scale; } positions[node] = { x: x, y: y }; if (assign) { graph.setNodeAttribute(node, options.attributes.x, x); graph.setNodeAttribute(node, options.attributes.y, y); } } return positions; } var circularLayout = genericCircularLayout.bind(null, false); circularLayout.assign = genericCircularLayout.bind(null, true); module.exports = circularLayout; },{"graphology-utils/is-graph":108,"lodash/defaultsDeep":200}],79:[function(require,module,exports){ /** * Graphology Layout * ================== * * Library endpoint. */ var circular = require('./circular.js'), random = require('./random.js'); exports.circular = circular; exports.random = random; },{"./circular.js":78,"./random.js":80}],80:[function(require,module,exports){ /** * Graphology Random Layout * ========================= * * Simple layout giving uniform random positions to the nodes. */ var defaults = require('lodash/defaultsDeep'), isGraph = require('graphology-utils/is-graph'); /** * Default options. */ var DEFAULTS = { attributes: { x: 'x', y: 'y' }, center: 0.5, rng: Math.random, scale: 1 }; /** * Abstract function running the layout. * * @param {Graph} graph - Target graph. * @param {object} [options] - Options: * @param {object} [attributes] - Attributes names to map. * @param {number} [center] - Center of the layout. * @param {function} [rng] - Custom RNG function to be used. * @param {number} [scale] - Scale of the layout. * @return {object} - The positions by node. */ function genericRandomLayout(assign, graph, options) { if (!isGraph(graph)) throw new Error('graphology-layout/random: the given graph is not a valid graphology instance.'); options = defaults(options, DEFAULTS); var positions = {}, nodes = graph.nodes(), center = options.center, rng = options.rng, scale = options.scale; var l = nodes.length, node, x, y, i; for (i = 0; i < l; i++) { node = nodes[i]; x = rng() * scale; y = rng() * scale; if (center !== 0.5) { x += center - 0.5 * scale; y += center - 0.5 * scale; } positions[node] = { x: x, y: y }; if (assign) { graph.setNodeAttribute(node, options.attributes.x, x); graph.setNodeAttribute(node, options.attributes.y, y); } } return positions; } var randomLayout = genericRandomLayout.bind(null, false); randomLayout.assign = genericRandomLayout.bind(null, true); module.exports = randomLayout; },{"graphology-utils/is-graph":108,"lodash/defaultsDeep":200}],81:[function(require,module,exports){ /** * Graphology Betweenness Centrality * ================================== * * Function computing betweenness centrality. */ var isGraph = require('graphology-utils/is-graph'), lib = require('graphology-shortest-path/indexed-brandes'), defaults = require('lodash/defaults'); var createUnweightedIndexedBrandes = lib.createUnweightedIndexedBrandes, createDijkstraIndexedBrandes = lib.createDijkstraIndexedBrandes; /** * Defaults. */ var DEFAULTS = { attributes: { centrality: 'betweennessCentrality', weight: 'weight' }, normalized: true, weighted: false }; /** * Abstract function computing beetweenness centrality for the given graph. * * @param {boolean} assign - Assign the results to node attributes? * @param {Graph} graph - Target graph. * @param {object} [options] - Options: * @param {object} [attributes] - Attribute names: * @param {string} [weight] - Name of the weight attribute. * @param {string} [centrality] - Name of the attribute to assign. * @param {boolean} [normalized] - Should the centrality be normalized? * @param {boolean} [weighted] - Weighted graph? * @param {object} */ function abstractBetweennessCentrality(assign, graph, options) { if (!isGraph(graph)) throw new Error('graphology-centrality/beetweenness-centrality: the given graph is not a valid graphology instance.'); // Solving options options = defaults({}, options, DEFAULTS); var weightAttribute = options.attributes.weight, centralityAttribute = options.attributes.centrality, normalized = options.normalized, weighted = options.weighted; var brandes = weighted ? createDijkstraIndexedBrandes(graph, weightAttribute) : createUnweightedIndexedBrandes(graph); var N = graph.order; var result, S, P, sigma, coefficient, i, j, m, v, w; var delta = new Float64Array(N), centralities = new Float64Array(N); // Iterating over each node for (i = 0; i < N; i++) { result = brandes(i); S = result[0]; P = result[1]; sigma = result[2]; // Accumulating j = S.size; while (j--) delta[S.items[S.size - j]] = 0; while (S.size !== 0) { w = S.pop(); coefficient = (1 + delta[w]) / sigma[w]; for (j = 0, m = P[w].length; j < m; j++) { v = P[w][j]; delta[v] += sigma[v] * coefficient; } if (w !== i) centralities[w] += delta[w]; } } // Rescaling var scale = null; if (normalized) scale = N <= 2 ? null : (1 / ((N - 1) * (N - 2))); else scale = graph.type === 'undirected' ? 0.5 : null; if (scale !== null) { for (i = 0; i < N; i++) centralities[i] *= scale; } if (assign) return brandes.index.assign(centralityAttribute, centralities); return brandes.index.collect(centralities); } /** * Exporting. */ var betweennessCentrality = abstractBetweennessCentrality.bind(null, false); betweennessCentrality.assign = abstractBetweennessCentrality.bind(null, true); module.exports = betweennessCentrality; },{"graphology-shortest-path/indexed-brandes":97,"graphology-utils/is-graph":108,"lodash/defaults":199}],82:[function(require,module,exports){ /** * Graphology Degree Centrality * ============================= * * Function computing degree centrality. */ var isGraph = require('graphology-utils/is-graph'); /** * Asbtract function to perform any kind of degree centrality. * * Intuitively, the degree centrality of a node is the fraction of nodes it * is connected to. * * @param {boolean} assign - Whether to assign the result to the nodes. * @param {string} method - Method of the graph to get the degree. * @param {Graph} graph - A graphology instance. * @param {object} [options] - Options: * @param {object} [attributes] - Custom attribute names: * @param {string} [centrality] - Name of the attribute to assign. * @return {object|void} */ function abstractDegreeCentrality(assign, method, graph, options) { var name = method + 'Centrality'; if (!isGraph(graph)) throw new Error('graphology-centrality/' + name + ': the given graph is not a valid graphology instance.'); if (method !== 'degree' && graph.type === 'undirected') throw new Error('graphology-centrality/' + name + ': cannot compute ' + method + ' centrality on an undirected graph.'); // Solving options options = options || {}; var attributes = options.attributes || {}; var centralityAttribute = attributes.centrality || name; // Variables var order = graph.order, nodes = graph.nodes(), getDegree = graph[method].bind(graph), centralities = {}; if (order === 0) return assign ? undefined : centralities; var s = 1 / (order - 1); // Iteration variables var node, centrality, i; for (i = 0; i < order; i++) { node = nodes[i]; centrality = getDegree(node) * s; if (assign) graph.setNodeAttribute(node, centralityAttribute, centrality); else centralities[node] = centrality; } return assign ? undefined : centralities; } /** * Building various functions to export. */ var degreeCentrality = abstractDegreeCentrality.bind(null, false, 'degree'), inDegreeCentrality = abstractDegreeCentrality.bind(null, false, 'inDegree'), outDegreeCentrality = abstractDegreeCentrality.bind(null, false, 'outDegree'); degreeCentrality.assign = abstractDegreeCentrality.bind(null, true, 'degree'); inDegreeCentrality.assign = abstractDegreeCentrality.bind(null, true, 'inDegree'); outDegreeCentrality.assign = abstractDegreeCentrality.bind(null, true, 'outDegree'); /** * Exporting. */ degreeCentrality.degreeCentrality = degreeCentrality; degreeCentrality.inDegreeCentrality = inDegreeCentrality; degreeCentrality.outDegreeCentrality = outDegreeCentrality; module.exports = degreeCentrality; },{"graphology-utils/is-graph":108}],83:[function(require,module,exports){ /** * Graphology Metrics Centrality * ============================== * * Sub module endpoint. */ exports.betweenness = require('./betweenness.js'); exports.degree = require('./degree.js'); },{"./betweenness.js":81,"./degree.js":82}],84:[function(require,module,exports){ /** * Graphology Degree * ================== * * Functions used to compute the degree of each node of a given graph. */ var isGraph = require('graphology-utils/is-graph'); var DEFAULT_ATTRIBUTES = { degree: 'degree', inDegree: 'inDegree', outDegree: 'outDegree', undirectedDegree: 'undirectedDegree', directedDegree: 'directedDegree' }; function abstractDegree(graph, callee, assign, type, options) { if (!isGraph(graph)) throw new Error('graphology-metrics/' + callee + ': given graph is not a valid graphology instance.'); if (graph.type === type) { throw new Error('graphology-metrics/' + callee + ': can not be calculated for ' + type + ' graphs.'); } var nodes = graph.nodes(); var i = 0; if (assign) { var attributes = Object.assign({}, DEFAULT_ATTRIBUTES, options && options.attributes); for (i = 0; i < nodes.length; i++) { graph.setNodeAttribute( nodes[i], attributes[callee], graph[callee](nodes[i]) ); } return; } var hashmap = {}; for (i = 0; i < nodes.length; i++) { hashmap[nodes[i]] = graph[callee](nodes[i]); } return hashmap; } function allDegree(graph, options, assign) { if (!isGraph(graph)) throw new Error('graphology-metrics/degree: given graph is not a valid graphology instance.'); var attributes = Object.assign({}, DEFAULT_ATTRIBUTES, options && options.attributes); var nodes = graph.nodes(); var types; var defaultTypes; if (graph.type === 'undirected') { defaultTypes = ['undirectedDegree']; } if (graph.type === 'mixed') { defaultTypes = ['inDegree', 'outDegree', 'undirectedDegree']; } if (graph.type === 'directed') { defaultTypes = ['inDegree', 'outDegree']; } if (options && options.types && options.types.length) { types = defaultTypes.filter(function(type) { return options.types.indexOf(type) > -1; }); } else { types = defaultTypes; } var i = 0; var j = 0; if (assign) { for (i = 0; i < nodes.length; i++) { for (j = 0; j < types.length; j++) { graph.setNodeAttribute( nodes[i], attributes[types[j]], graph[types[j]](nodes[i]) ); } } } else { var hashmap = {}; for (i = 0; i < nodes.length; i++) { var response = {}; for (j = 0; j < types.length; j++) { response[attributes[types[j]]] = graph[types[j]](nodes[i]); } hashmap[nodes[i]] = response; } return hashmap; } } allDegree.assign = function assignAllDegree(graph, options) { allDegree(graph, options, true); }; function degree(graph) { return abstractDegree(graph, 'degree'); } degree.assign = function assignDegree(graph, options) { abstractDegree(graph, 'degree', true, 'none', options); }; function inDegree(graph) { return abstractDegree(graph, 'inDegree', false, 'undirected'); } inDegree.assign = function assignInDegree(graph, options) { abstractDegree(graph, 'inDegree', true, 'undirected', options); }; function outDegree(graph) { return abstractDegree(graph, 'outDegree', false, 'undirected'); } outDegree.assign = function assignOutDegree(graph, option) { abstractDegree(graph, 'outDegree', true, 'undirected', option); }; function undirectedDegree(graph) { return abstractDegree(graph, 'undirectedDegree', false, 'directed'); } undirectedDegree.assign = function assignUndirectedDegree(graph, option) { abstractDegree(graph, 'undirectedDegree', true, 'directed', option); }; function directedDegree(graph) { return abstractDegree(graph, 'directedDegree', false, 'undirected'); } directedDegree.assign = function assignUndirectedDegree(graph, option) { abstractDegree(graph, 'directedDegree', true, 'undirected', option); }; degree.inDegree = inDegree; degree.outDegree = outDegree; degree.undirectedDegree = undirectedDegree; degree.directedDegree = directedDegree; degree.allDegree = allDegree; degree.abstractDegree = abstractDegree; module.exports = degree; },{"graphology-utils/is-graph":108}],85:[function(require,module,exports){ /** * Graphology Density * =================== * * Functions used to compute the density of the given graph. */ var isGraph = require('graphology-utils/is-graph'); /** * Returns the undirected density. * * @param {number} order - Number of nodes in the graph. * @param {number} size - Number of edges in the graph. * @return {number} */ function undirectedDensity(order, size) { return 2 * size / (order * (order - 1)); } /** * Returns the directed density. * * @param {number} order - Number of nodes in the graph. * @param {number} size - Number of edges in the graph. * @return {number} */ function directedDensity(order, size) { return size / (order * (order - 1)); } /** * Returns the mixed density. * * @param {number} order - Number of nodes in the graph. * @param {number} size - Number of edges in the graph. * @return {number} */ function mixedDensity(order, size) { var d = (order * (order - 1)); return ( size / (d + d / 2) ); } /** * Returns the size a multi graph would have if it were a simple one. * * @param {Graph} graph - Target graph. * @return {number} */ function simpleSizeForMultiGraphs(graph) { var nodes = graph.nodes(), size = 0, i, l; for (i = 0, l = nodes.length; i < l; i++) { size += graph.outNeighbors(nodes[i]).length; size += graph.undirectedNeighbors(nodes[i]).length / 2; } return size; } /** * Returns the density for the given parameters. * * Arity 3: * @param {boolean} type - Type of density. * @param {boolean} multi - Compute multi density? * @param {Graph} graph - Target graph. * * Arity 4: * @param {boolean} type - Type of density. * @param {boolean} multi - Compute multi density? * @param {number} order - Number of nodes in the graph. * @param {number} size - Number of edges in the graph. * * @return {number} */ function abstractDensity(type, multi, graph) { var order, size; // Retrieving order & size if (arguments.length > 3) { order = graph; size = arguments[3]; if (typeof order !== 'number') throw new Error('graphology-metrics/density: given order is not a number.'); if (typeof size !== 'number') throw new Error('graphology-metrics/density: given size is not a number.'); } else { if (!isGraph(graph)) throw new Error('graphology-metrics/density: given graph is not a valid graphology instance.'); order = graph.order; size = graph.size; if (graph.multi && multi === false) size = simpleSizeForMultiGraphs(graph); } // When the graph has only one node, its density is 0 if (order < 2) return 0; // Guessing type & multi if (type === null) type = graph.type; if (multi === null) multi = graph.multi; // Getting the correct function var fn; if (type === 'undirected') fn = undirectedDensity; else if (type === 'directed') fn = directedDensity; else fn = mixedDensity; // Applying the function return fn(order, size); } /** * Creating the exported functions. */ var density = abstractDensity.bind(null, null, null); density.directedDensity = abstractDensity.bind(null, 'directed', false); density.undirectedDensity = abstractDensity.bind(null, 'undirected', false); density.mixedDensity = abstractDensity.bind(null, 'mixed', false); density.multiDirectedDensity = abstractDensity.bind(null, 'directed', true); density.multiUndirectedDensity = abstractDensity.bind(null, 'undirected', true); density.multiMixedDensity = abstractDensity.bind(null, 'mixed', true); /** * Exporting. */ module.exports = density; },{"graphology-utils/is-graph":108}],86:[function(require,module,exports){ /** * Graphology Diameter * ======================== * * Functions used to compute the diameter of the given graph. */ var isGraph = require('graphology-utils/is-graph'); var eccentricity = require('./eccentricity.js'); module.exports = function diameter(graph) { if (!isGraph(graph)) throw new Error('graphology-metrics/diameter: given graph is not a valid graphology instance.'); if (graph.size === 0) return Infinity; var diameter = -Infinity, ecc = 0; var nodes = graph.nodes() for (var i = 0, l = nodes.length; i < l ; i++) { ecc = eccentricity(graph, nodes[i]); if (ecc > diameter) diameter = ecc; if (diameter === Infinity) break; } return diameter; }; },{"./eccentricity.js":87,"graphology-utils/is-graph":108}],87:[function(require,module,exports){ /** * Graphology Eccentricity * ======================== * * Functions used to compute the eccentricity of each node of a given graph. */ var isGraph = require('graphology-utils/is-graph'); var singleSourceLength = require('graphology-shortest-path/unweighted').singleSourceLength; module.exports = function eccentricity(graph, node) { if (!isGraph(graph)) throw new Error('graphology-metrics/eccentricity: given graph is not a valid graphology instance.'); if (graph.size === 0) return Infinity; var ecc = -Infinity; var lengths = singleSourceLength(graph, node); var otherNode; var pathLength, l = 0; for (otherNode in lengths) { pathLength = lengths[otherNode]; if (pathLength > ecc) ecc = pathLength; l++; } if (l < graph.order) return Infinity; return ecc; }; },{"graphology-shortest-path/unweighted":105,"graphology-utils/is-graph":108}],88:[function(require,module,exports){ /** * Graphology Extent * ================== * * Simple function returning the extent of selected attributes of the graph. */ var isGraph = require('graphology-utils/is-graph'); /** * Function returning the extent of the selected node attributes. * * @param {Graph} graph - Target graph. * @param {string|array} attribute - Single or multiple attributes. * @return {array|object} */ function nodeExtent(graph, attribute) { if (!isGraph(graph)) throw new Error('graphology-metrics/extent: the given graph is not a valid graphology instance.'); var attributes = [].concat(attribute); var nodes = graph.nodes(), node, data, value, key, a, i, l; var results = {}; for (a = 0; a < attributes.length; a++) { key = attributes[a]; results[key] = [Infinity, -Infinity]; } for (i = 0, l = nodes.length; i < l; i++) { node = nodes[i]; data = graph.getNodeAttributes(node); for (a = 0; a < attributes.length; a++) { key = attributes[a]; value = data[key]; if (value < results[key][0]) results[key][0] = value; if (value > results[key][1]) results[key][1] = value; } } return typeof attribute === 'string' ? results[attribute] : results; } /** * Function returning the extent of the selected edge attributes. * * @param {Graph} graph - Target graph. * @param {string|array} attribute - Single or multiple attributes. * @return {array|object} */ function edgeExtent(graph, attribute) { if (!isGraph(graph)) throw new Error('graphology-metrics/extent: the given graph is not a valid graphology instance.'); var attributes = [].concat(attribute); var edges = graph.edges(), edge, data, value, key, a, i, l; var results = {}; for (a = 0; a < attributes.length; a++) { key = attributes[a]; results[key] = [Infinity, -Infinity]; } for (i = 0, l = edges.length; i < l; i++) { edge = edges[i]; data = graph.getEdgeAttributes(edge); for (a = 0; a < attributes.length; a++) { key = attributes[a]; value = data[key]; if (value < results[key][0]) results[key][0] = value; if (value > results[key][1]) results[key][1] = value; } } return typeof attribute === 'string' ? results[attribute] : results; } /** * Exporting. */ var extent = nodeExtent; extent.nodeExtent = nodeExtent; extent.edgeExtent = edgeExtent; module.exports = extent; },{"graphology-utils/is-graph":108}],89:[function(require,module,exports){ /** * Graphology Metrics * =================== * * Library endpoint. */ exports.centrality = require('./centrality'); exports.density = require('./density.js'); exports.diameter = require('./diameter.js'); exports.eccentricity = require('./eccentricity.js'); exports.extent = require('./extent.js'); exports.layoutQuality = require('./layout-quality'); exports.modularity = require('./modularity.js'); exports.weightedDegree = require('./weighted-degree.js'); exports.weightedSize = require('./weighted-size.js'); },{"./centrality":83,"./density.js":85,"./diameter.js":86,"./eccentricity.js":87,"./extent.js":88,"./layout-quality":91,"./modularity.js":94,"./weighted-degree.js":95,"./weighted-size.js":96}],90:[function(require,module,exports){ /** * Graphology Layout Quality - Edge Uniformity * ============================================ * * Function computing the layout quality metric named "edge uniformity". * It is basically the normalized standard deviation of edge length. * * [Article]: * Rahman, Md Khaledur, et al. « BatchLayout: A Batch-Parallel Force-Directed * Graph Layout Algorithm in Shared Memory ». * http://arxiv.org/abs/2002.08233. */ var isGraph = require('graphology-utils/is-graph'); function euclideanDistance(a, b) { return Math.sqrt( Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2) ); } module.exports = function edgeUniformity(graph) { if (!isGraph(graph)) throw new Error('graphology-metrics/layout-quality/edge-uniformity: given graph is not a valid graphology instance.'); if (graph.size === 0) return 0; var sum = 0, i = 0, l; var lengths = new Float64Array(graph.size); graph.forEachEdge(function(edge, attr, source, target, sourceAttr, targetAttr) { var edgeLength = euclideanDistance(sourceAttr, targetAttr); lengths[i++] = edgeLength; sum += edgeLength; }); var avg = sum / graph.size; var stdev = 0; for (i = 0, l = graph.size; i < l; i++) stdev += Math.pow(avg - lengths[i], 2); var metric = stdev / (graph.size * Math.pow(avg, 2)); return Math.sqrt(metric); }; },{"graphology-utils/is-graph":108}],91:[function(require,module,exports){ exports.edgeUniformity = require('./edge-uniformity.js'); exports.neighborhoodPreservation = require('./neighborhood-preservation.js'); exports.stress = require('./stress.js'); },{"./edge-uniformity.js":90,"./neighborhood-preservation.js":92,"./stress.js":93}],92:[function(require,module,exports){ /** * Graphology Layout Quality - Neighborhood Preservation * ====================================================== * * Function computing the layout quality metric named "neighborhood preservation". * It is basically the average of overlap coefficient between node neighbors in * the graph and equivalent k-nn in the 2d layout space. * * [Article]: * Rahman, Md Khaledur, et al. « BatchLayout: A Batch-Parallel Force-Directed * Graph Layout Algorithm in Shared Memory ». * http://arxiv.org/abs/2002.08233. */ var isGraph = require('graphology-utils/is-graph'), KDTree = require('mnemonist/kd-tree'), intersectionSize = require('mnemonist/set').intersectionSize; module.exports = function neighborhoodPreservation(graph) { if (!isGraph(graph)) throw new Error('graphology-metrics/layout-quality/neighborhood-preservation: given graph is not a valid graphology instance.'); if (graph.order === 0) throw new Error('graphology-metrics/layout-quality/neighborhood-preservation: cannot compute stress for a null graph.'); if (graph.size === 0) return 0; var axes = [new Float64Array(graph.order), new Float64Array(graph.order)], i = 0; graph.forEachNode(function(node, attr) { axes[0][i] = attr.x; axes[1][i++] = attr.y; }); var tree = KDTree.fromAxes(axes, graph.nodes()); var sum = 0; graph.forEachNode(function(node, attr) { var neighbors = new Set(graph.neighbors(node)); // If node has no neighbors or is connected to every other node if (neighbors.size === 0 || neighbors.size === graph.order - 1) { sum += 1; return; } var knn = tree.kNearestNeighbors(neighbors.size + 1, [attr.x, attr.y]); knn = new Set(knn.slice(1)); var I = intersectionSize(neighbors, knn); // Computing overlap coefficient sum += I / knn.size; }); return sum / graph.order; }; },{"graphology-utils/is-graph":108,"mnemonist/kd-tree":226,"mnemonist/set":227}],93:[function(require,module,exports){ /** * Graphology Layout Quality - Stress * =================================== * * Function computing the layout quality metric named "stress". * It is basically the sum of normalized deltas between graph topology distances * and 2d space distances of the layout. * * [Article]: * Rahman, Md Khaledur, et al. « BatchLayout: A Batch-Parallel Force-Directed * Graph Layout Algorithm in Shared Memory ». * http://arxiv.org/abs/2002.08233. */ var isGraph = require('graphology-utils/is-graph'), undirectedSingleSourceLength = require('graphology-shortest-path/unweighted').undirectedSingleSourceLength; function euclideanDistance(a, b) { return Math.sqrt( Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2) ); } module.exports = function stress(graph) { if (!isGraph(graph)) throw new Error('graphology-metrics/layout-quality/stress: given graph is not a valid graphology instance.'); if (graph.order === 0) throw new Error('graphology-metrics/layout-quality/stress: cannot compute stress for a null graph.'); var nodes = new Array(graph.order), entries = new Array(graph.order), i = 0; // We choose an arbitrary large distance for when two nodes cannot be // connected because they belong to different connected components // and because we cannot deal with Infinity in our computations // This is what most papers recommend anyway var maxDistance = graph.order * 4; graph.forEachNode(function(node, attr) { nodes[i] = node; entries[i++] = attr; }); var j, l, p1, p2, shortestPaths, dij, wij, cicj; var sum = 0; for (i = 0, l = graph.order; i < l; i++) { shortestPaths = undirectedSingleSourceLength(graph, nodes[i]); p1 = entries[i]; for (j = i + 1; j < l; j++) { p2 = entries[j]; // NOTE: dij should be 0 since we don't consider self-loops dij = shortestPaths[nodes[j]]; // Target is in another castle if (typeof dij === 'undefined') dij = maxDistance; cicj = euclideanDistance(p1, p2); wij = 1 / (dij * dij); sum += wij * Math.pow(cicj - dij, 2); } } return sum; }; },{"graphology-shortest-path/unweighted":105,"graphology-utils/is-graph":108}],94:[function(require,module,exports){ /** * Graphology Modularity * ====================== * * Implementation of network modularity for graphology. * * Modularity is a bit of a tricky problem because there are a wide array * of different definitions and implementations. The current implementation * try to stay true to Newman's original definition and consider both the * undirected & directed case as well as the weighted one. The current * implementation should also be aligned with Louvain algorithm's definition * of the metric. * * Regarding the directed version, one has to understand that the undirected * version's is basically considering the graph as a directed one where all * edges would be mutual. * * There is one exception to this, though: self loops. To conform with density's * definition, as used in modularity's one, and to keep true to the matrix * formulation of modularity, one has to note that self-loops only count once * in both the undirected and directed cases. This means that a k-clique with * one node having a self-loop will not have the same modularity in the * undirected and mutual case. Indeed, in both cases the modularity of a * k-clique with one loop and minus one internal edge should be equal. * * This also means that, as with the naive density formula regarding loops, * one should increment M when considering a loop. Also, to remain coherent * in this regard, degree should not be multiplied by two because of the loop * else it will have too much importance regarding the considered proportions. * * Hence, here are the retained formulas: * * For dense weighted undirected network: * -------------------------------------- * * Q = 1/2m * [ ∑ij[Aij - (di.dj / 2m)] * ∂(ci, cj) ] * * where: * - i & j being a pair of nodes * - m is the sum of edge weights * - Aij being the weight of the ij edge (or 0 if absent) * - di being the weighted degree of node i * - ci being the community to which belongs node i * - ∂ is Kronecker's delta function (1 if x = y else 0) * * For dense weighted directed network: * ------------------------------------ * * Qd = 1/m * [ ∑ij[Aij - (dini.doutj / m)] * ∂(ci, cj) ] * * where: * - dini is the in degree of node i * - douti is the out degree of node i * * For sparse weighted undirected network: * --------------------------------------- * * Q = ∑c[ (∑cinternal / 2m) - (∑ctotal / 2m)² ] * * where: * - c is a community * - ∑cinternal is the total weight of a community internal edges * - ∑ctotal is the total weight of edges connected to a community * * For sparse weighted directed network: * ------------------------------------- * * Qd = ∑c[ (∑cinternal / m) - (∑cintotal * ∑couttotal / m²) ] * * where: * - ∑cintotal is the total weight of edges pointing towards a community * - ∑couttotal is the total weight of edges going from a community * * Note that dense version run in O(N²) while sparse version runs in O(V). So * the dense version is mostly here to guarantee the validity of the sparse one. * As such it is not used as default. * * For undirected delta computation: * --------------------------------- * * ∆Q = (dic / 2m) - ((∑ctotal * di) / 2m²) * * where: * - dic is the degree of the node in community c * * For directed delta computation: * ------------------------------- * * ∆Qd = (dic / m) - (((douti * ∑cintotal) + (dini * ∑couttotal)) / m²) * * Gephi's version of undirected delta computation: * ------------------------------------------------ * * ∆Qgephi = dic - (di * Ztot) / 2m * * Note that the above formula is erroneous and should really be: * * ∆Qgephi = dic - (di * Ztot) / m * * because then: ∆Qgephi = ∆Q * 2m * * It is used because it is faster to compute. Since Gephi's error is only by * a constant factor, it does not make the result incorrect. * * [Latex] * * Sparse undirected * Q = \sum_{c} \bigg{[} \frac{\sum\nolimits_{c\,in}}{2m} - \left(\frac{\sum\nolimits_{c\,tot}}{2m}\right )^2 \bigg{]} * * Sparse directed * Q_d = \sum_{c} \bigg{[} \frac{\sum\nolimits_{c\,in}}{m} - \frac{\sum_{c\,tot}^{in}\sum_{c\,tot}^{out}}{m^2} \bigg{]} * * [Articles] * M. E. J. Newman, « Modularity and community structure in networks », * Proc. Natl. Acad. Sci. USA, vol. 103, no 23,‎ 2006, p. 8577–8582 * https://dx.doi.org/10.1073%2Fpnas.0601602103 * * Newman, M. E. J. « Community detection in networks: Modularity optimization * and maximum likelihood are equivalent ». Physical Review E, vol. 94, no 5, * novembre 2016, p. 052315. arXiv.org, doi:10.1103/PhysRevE.94.052315. * https://arxiv.org/pdf/1606.02319.pdf * * Blondel, Vincent D., et al. « Fast unfolding of communities in large * networks ». Journal of Statistical Mechanics: Theory and Experiment, * vol. 2008, no 10, octobre 2008, p. P10008. DOI.org (Crossref), * doi:10.1088/1742-5468/2008/10/P10008. * https://arxiv.org/pdf/0803.0476.pdf * * Nicolas Dugué, Anthony Perez. Directed Louvain: maximizing modularity in * directed networks. [Research Report] Université d’Orléans. 2015. hal-01231784 * https://hal.archives-ouvertes.fr/hal-01231784 * * R. Lambiotte, J.-C. Delvenne and M. Barahona. Laplacian Dynamics and * Multiscale Modular Structure in Networks, * doi:10.1109/TNSE.2015.2391998. * https://arxiv.org/abs/0812.1770 * * [ToDo]: * - Resolution limit. * * [Links]: * https://math.stackexchange.com/questions/2637469/where-does-the-second-formula-of-modularity-comes-from-in-the-louvain-paper-the * https://www.quora.com/How-is-the-formula-for-Louvain-modularity-change-derived * https://github.com/gephi/gephi/blob/master/modules/StatisticsPlugin/src/main/java/org/gephi/statistics/plugin/Modularity.java * https://github.com/igraph/igraph/blob/eca5e809aab1aa5d4eca1e381389bcde9cf10490/src/community.c#L906 */ var defaults = require('lodash/defaultsDeep'), isGraph = require('graphology-utils/is-graph'), inferType = require('graphology-utils/infer-type'); var DEFAULTS = { attributes: { community: 'community', weight: 'weight' }, communities: null, resolution: 1, weighted: true }; function createWeightGetter(weighted, weightAttribute) { return function(attr) { if (!attr) return 0; if (!weighted) return 1; var w = attr[weightAttribute]; if (typeof w !== 'number') w = 1; return w; }; } function collectForUndirectedDense(graph, options) { var communities = new Array(graph.order), weightedDegrees = new Float64Array(graph.order), M = 0; var ids = {}; var getWeight = createWeightGetter(options.weighted, options.attributes.weight); // Collecting communities var i = 0; graph.forEachNode(function(node, attr) { ids[node] = i; communities[i++] = options.communities ? options.communities[node] : attr[options.attributes.community]; }); // Collecting weights graph.forEachUndirectedEdge(function(edge, attr, source, target) { var weight = getWeight(attr); M += weight; weightedDegrees[ids[source]] += weight; // NOTE: we double degree only if we don't have a loop if (source !== target) weightedDegrees[ids[target]] += weight; }); return { getWeight: getWeight, communities: communities, weightedDegrees: weightedDegrees, M: M }; } function collectForDirectedDense(graph, options) { var communities = new Array(graph.order), weightedInDegrees = new Float64Array(graph.order), weightedOutDegrees = new Float64Array(graph.order), M = 0; var ids = {}; var getWeight = createWeightGetter(options.weighted, options.attributes.weight); // Collecting communities var i = 0; graph.forEachNode(function(node, attr) { ids[node] = i; communities[i++] = options.communities ? options.communities[node] : attr[options.attributes.community]; }); // Collecting weights graph.forEachDirectedEdge(function(edge, attr, source, target) { var weight = getWeight(attr); M += weight; weightedOutDegrees[ids[source]] += weight; weightedInDegrees[ids[target]] += weight; }); return { getWeight: getWeight, communities: communities, weightedInDegrees: weightedInDegrees, weightedOutDegrees: weightedOutDegrees, M: M }; } function undirectedDenseModularity(graph, options) { var resolution = options.resolution; var result = collectForUndirectedDense(graph, options); var communities = result.communities, weightedDegrees = result.weightedDegrees; var M = result.M; var nodes = graph.nodes(); var i, j, l, Aij, didj; var S = 0; var M2 = M * 2; for (i = 0, l = graph.order; i < l; i++) { // NOTE: it is important to parse the whole matrix here, diagonal and // lower part included. A lot of implementation differ here because // they process only a part of the matrix for (j = 0; j < l; j++) { // NOTE: Kronecker's delta // NOTE: we could go from O(n^2) to O(avg.C^2) if (communities[i] !== communities[j]) continue; edgeAttributes = graph.undirectedEdge(nodes[i], nodes[j]); Aij = result.getWeight(edgeAttributes); didj = weightedDegrees[i] * weightedDegrees[j]; // We add twice if we have a self loop if (i === j && typeof edgeAttributes !== 'undefined') S += (Aij - (didj / M2) * resolution) * 2; else S += (Aij - (didj / M2) * resolution); } } return S / M2; } function directedDenseModularity(graph, options) { var resolution = options.resolution; var result = collectForDirectedDense(graph, options); var communities = result.communities, weightedInDegrees = result.weightedInDegrees, weightedOutDegrees = result.weightedOutDegrees; var M = result.M; var nodes = graph.nodes(); var i, j, l, Aij, didj; var S = 0; for (i = 0, l = graph.order; i < l; i++) { // NOTE: it is important to parse the whole matrix here, diagonal and // lower part included. A lot of implementation differ here because // they process only a part of the matrix for (j = 0; j < l; j++) { // NOTE: Kronecker's delta // NOTE: we could go from O(n^2) to O(avg.C^2) if (communities[i] !== communities[j]) continue; edgeAttributes = graph.directedEdge(nodes[i], nodes[j]); Aij = result.getWeight(edgeAttributes); didj = weightedInDegrees[i] * weightedOutDegrees[j]; // Here we multiply by two to simulate iteration through lower part S += Aij - (didj / M) * resolution; } } return S / M; } function collectCommunitesForUndirected(graph, options) { var communities = {}, totalWeights = {}, internalWeights = {}; if (options.communities) communities = options.communities; graph.forEachNode(function(node, attr) { var community; if (!options.communities) { community = attr[options.attributes.community]; communities[node] = community; } else { community = communities[node]; } if (typeof community === 'undefined') throw new Error('graphology-metrics/modularity: the "' + node + '" node is not in the partition.'); totalWeights[community] = 0; internalWeights[community] = 0; }); return { communities: communities, totalWeights: totalWeights, internalWeights: internalWeights }; } function collectCommunitesForDirected(graph, options) { var communities = {}, totalInWeights = {}, totalOutWeights = {}, internalWeights = {}; if (options.communities) communities = options.communities; graph.forEachNode(function(node, attr) { var community; if (!options.communities) { community = attr[options.attributes.community]; communities[node] = community; } else { community = communities[node]; } if (typeof community === 'undefined') throw new Error('graphology-metrics/modularity: the "' + node + '" node is not in the partition.'); totalInWeights[community] = 0; totalOutWeights[community] = 0; internalWeights[community] = 0; }); return { communities: communities, totalInWeights: totalInWeights, totalOutWeights: totalOutWeights, internalWeights: internalWeights }; } function undirectedSparseModularity(graph, options) { var resolution = options.resolution; var result = collectCommunitesForUndirected(graph, options); var M = 0; var totalWeights = result.totalWeights, internalWeights = result.internalWeights, communities = result.communities; var getWeight = createWeightGetter(options.weighted, options.attributes.weight); graph.forEachUndirectedEdge(function(edge, edgeAttr, source, target, sourceAttr, targetAttr) { var weight = getWeight(edgeAttr); M += weight; var sourceCommunity = communities[source]; var targetCommunity = communities[target]; totalWeights[sourceCommunity] += weight; totalWeights[targetCommunity] += weight; if (sourceCommunity !== targetCommunity) return; internalWeights[sourceCommunity] += weight * 2; }); var Q = 0, M2 = M * 2; for (var C in internalWeights) Q += internalWeights[C] / M2 - Math.pow(totalWeights[C] / M2, 2) * resolution; return Q; } function directedSparseModularity(graph, options) { var resolution = options.resolution; var result = collectCommunitesForDirected(graph, options); var M = 0; var totalInWeights = result.totalInWeights, totalOutWeights = result.totalOutWeights, internalWeights = result.internalWeights, communities = result.communities; var getWeight = createWeightGetter(options.weighted, options.attributes.weight); graph.forEachDirectedEdge(function(edge, edgeAttr, source, target, sourceAttr, targetAttr) { var weight = getWeight(edgeAttr); M += weight; var sourceCommunity = communities[source]; var targetCommunity = communities[target]; totalOutWeights[sourceCommunity] += weight; totalInWeights[targetCommunity] += weight; if (sourceCommunity !== targetCommunity) return; internalWeights[sourceCommunity] += weight; }); var Q = 0; for (var C in internalWeights) Q += (internalWeights[C] / M) - (totalInWeights[C] * totalOutWeights[C] / Math.pow(M, 2)) * resolution; return Q; } // NOTE: the formula is a bit unclear here but nodeCommunityDegree should be // given as the edges count * 2 function undirectedModularityDelta(M, communityTotalWeight, nodeDegree, nodeCommunityDegree) { return ( (nodeCommunityDegree / (2 * M)) - ( (communityTotalWeight * nodeDegree) / (2 * (M * M)) ) ); } function directedModularityDelta(M, communityTotalInWeight, communityTotalOutWeight, nodeInDegree, nodeOutDegree, nodeCommunityDegree) { return ( (nodeCommunityDegree / M) - ( ((nodeOutDegree * communityTotalInWeight) + (nodeInDegree * communityTotalOutWeight)) / (M * M) ) ); } function denseModularity(graph, options) { if (!isGraph(graph)) throw new Error('graphology-metrics/modularity: given graph is not a valid graphology instance.'); if (graph.size === 0) throw new Error('graphology-metrics/modularity: cannot compute modularity of an empty graph.'); if (graph.multi) throw new Error('graphology-metrics/modularity: cannot compute modularity of a multi graph. Cast it to a simple one beforehand.'); var trueType = inferType(graph); if (trueType === 'mixed') throw new Error('graphology-metrics/modularity: cannot compute modularity of a mixed graph.'); options = defaults({}, options || {}, DEFAULTS); if (trueType === 'directed') return directedDenseModularity(graph, options); return undirectedDenseModularity(graph, options); } function sparseModularity(graph, options) { if (!isGraph(graph)) throw new Error('graphology-metrics/modularity: given graph is not a valid graphology instance.'); if (graph.size === 0) throw new Error('graphology-metrics/modularity: cannot compute modularity of an empty graph.'); if (graph.multi) throw new Error('graphology-metrics/modularity: cannot compute modularity of a multi graph. Cast it to a simple one beforehand.'); var trueType = inferType(graph); if (trueType === 'mixed') throw new Error('graphology-metrics/modularity: cannot compute modularity of a mixed graph.'); options = defaults({}, options || {}, DEFAULTS); if (trueType === 'directed') return directedSparseModularity(graph, options); return undirectedSparseModularity(graph, options); } var modularity = sparseModularity; modularity.sparse = sparseModularity; modularity.dense = denseModularity; modularity.undirectedDelta = undirectedModularityDelta; modularity.directedDelta = directedModularityDelta; module.exports = modularity; },{"graphology-utils/infer-type":106,"graphology-utils/is-graph":108,"lodash/defaultsDeep":200}],95:[function(require,module,exports){ /** * Graphology Weighted Degree * =========================== * * Function computing the weighted degree of nodes. The weighted degree is the * sum of a node's edges' weights. */ var isGraph = require('graphology-utils/is-graph'); /** * Defaults. */ var DEFAULT_WEIGHT_ATTRIBUTE = 'weight'; /** * Asbtract function to perform any kind of weighted degree. * * Signature n°1 - computing weighted degree for every node: * * @param {string} name - Name of the implemented function. * @param {boolean} assign - Whether to assign the result to the nodes. * @param {string} method - Method of the graph to get the edges. * @param {Graph} graph - A graphology instance. * @param {object} [options] - Options: * @param {object} [attributes] - Custom attribute names: * @param {string} [weight] - Name of the weight attribute. * @param {string} [weightedDegree] - Name of the attribute to set. * * Signature n°2 - computing weighted degree for a single node: * * @param {string} name - Name of the implemented function. * @param {boolean} assign - Whether to assign the result to the nodes. * @param {string} edgeGetter - Graph's method used to get edges. * @param {Graph} graph - A graphology instance. * @param {any} node - Key of node. * @param {object} [options] - Options: * @param {object} [attributes] - Custom attribute names: * @param {string} [weight] - Name of the weight attribute. * @param {string} [weightedDegree] - Name of the attribute to set. * * @return {object|void} */ function abstractWeightedDegree(name, assign, edgeGetter, graph, options) { if (!isGraph(graph)) throw new Error('graphology-metrics/' + name + ': the given graph is not a valid graphology instance.'); if (edgeGetter !== 'edges' && graph.type === 'undirected') throw new Error('graphology-metrics/' + name + ': cannot compute ' + name + ' on an undirected graph.'); var singleNode = null; // Solving arguments if (arguments.length === 5 && typeof arguments[4] !== 'object') { singleNode = arguments[4]; } else if (arguments.length === 6) { singleNode = arguments[4]; options = arguments[5]; } // Solving options options = options || {}; var attributes = options.attributes || {}; var weightAttribute = attributes.weight || DEFAULT_WEIGHT_ATTRIBUTE, weightedDegreeAttribute = attributes.weightedDegree || name; var edges, d, w, i, l; // Computing weighted degree for a single node if (singleNode) { edges = graph[edgeGetter](singleNode); d = 0; for (i = 0, l = edges.length; i < l; i++) { w = graph.getEdgeAttribute(edges[i], weightAttribute); if (typeof w === 'number') d += w; } if (assign) { graph.setNodeAttribute(singleNode, weightedDegreeAttribute, d); return; } else { return d; } } // Computing weighted degree for every node // TODO: it might be more performant to iterate on the edges here. var nodes = graph.nodes(), node, weightedDegrees = {}, j, m; for (i = 0, l = nodes.length; i < l; i++) { node = nodes[i]; edges = graph[edgeGetter](node); d = 0; for (j = 0, m = edges.length; j < m; j++) { w = graph.getEdgeAttribute(edges[j], weightAttribute); if (typeof w === 'number') d += w; } if (assign) graph.setNodeAttribute(node, weightedDegreeAttribute, d); else weightedDegrees[node] = d; } if (!assign) return weightedDegrees; } /** * Building various functions to export. */ var weightedDegree = abstractWeightedDegree.bind(null, 'weightedDegree', false, 'edges'), weightedInDegree = abstractWeightedDegree.bind(null, 'weightedInDegree', false, 'inEdges'), weightedOutDegree = abstractWeightedDegree.bind(null, 'weightedOutDegree', false, 'outEdges'); weightedDegree.assign = abstractWeightedDegree.bind(null, 'weightedDegree', true, 'edges'); weightedInDegree.assign = abstractWeightedDegree.bind(null, 'weightedInDegree', true, 'inEdges'); weightedOutDegree.assign = abstractWeightedDegree.bind(null, 'weightedOutDegree', true, 'outEdges'); /** * Exporting. */ weightedDegree.weightedDegree = weightedDegree; weightedDegree.weightedInDegree = weightedInDegree; weightedDegree.weightedOutDegree = weightedOutDegree; module.exports = weightedDegree; },{"graphology-utils/is-graph":108}],96:[function(require,module,exports){ /** * Graphology Weighted Size * ========================= * * Function returning the sum of the graph's edges' weights. */ var isGraph = require('graphology-utils/is-graph'); /** * Defaults. */ var DEFAULT_WEIGHT_ATTRIBUTE = 'weight'; /** * Weighted size function. * * @param {Graph} graph - Target graph. * @param {string} [weightAttribute] - Name of the weight attribute. * @return {number} */ module.exports = function weightedSize(graph, weightAttribute) { // Handling errors if (!isGraph(graph)) throw new Error('graphology-metrics/weighted-size: the given graph is not a valid graphology instance.'); weightAttribute = weightAttribute || DEFAULT_WEIGHT_ATTRIBUTE; var edges = graph.edges(), W = 0, w, i, l; for (i = 0, l = edges.length; i < l; i++) { w = graph.getEdgeAttribute(edges[i], weightAttribute); if (typeof w === 'number') W += w; } return W; }; },{"graphology-utils/is-graph":108}],97:[function(require,module,exports){ /** * Graphology Indexed Brandes Routine * =================================== * * Indexed version of the famous Brandes routine aiming at computing * betweenness centrality efficiently. */ var FixedDeque = require('mnemonist/fixed-deque'), FixedStack = require('mnemonist/fixed-stack'), Heap = require('mnemonist/heap'), typed = require('mnemonist/utils/typed-arrays'), neighborhoodIndices = require('graphology-indices/neighborhood/outbound'); var OutboundNeighborhoodIndex = neighborhoodIndices.OutboundNeighborhoodIndex, WeightedOutboundNeighborhoodIndex = neighborhoodIndices.WeightedOutboundNeighborhoodIndex; /** * Indexed unweighted Brandes routine. * * [Reference]: * Ulrik Brandes: A Faster Algorithm for Betweenness Centrality. * Journal of Mathematical Sociology 25(2):163-177, 2001. * * @param {Graph} graph - The graphology instance. * @return {function} */ exports.createUnweightedIndexedBrandes = function createUnweightedIndexedBrandes(graph) { var neighborhoodIndex = new OutboundNeighborhoodIndex(graph); var neighborhood = neighborhoodIndex.neighborhood, starts = neighborhoodIndex.starts; var order = graph.order; var S = new FixedStack(typed.getPointerArray(order), order), sigma = new Uint32Array(order), P = new Array(order), D = new Int32Array(order); var Q = new FixedDeque(Uint32Array, order); var brandes = function(sourceIndex) { var Dv, sigmav, start, stop, j, v, w; for (v = 0; v < order; v++) { P[v] = []; sigma[v] = 0; D[v] = -1; } sigma[sourceIndex] = 1; D[sourceIndex] = 0; Q.push(sourceIndex); while (Q.size !== 0) { v = Q.shift(); S.push(v); Dv = D[v]; sigmav = sigma[v]; start = starts[v]; stop = starts[v + 1]; for (j = start; j < stop; j++) { w = neighborhood[j]; if (D[w] === -1) { Q.push(w); D[w] = Dv + 1; } if (D[w] === Dv + 1) { sigma[w] += sigmav; P[w].push(v); } } } return [S, P, sigma]; }; brandes.index = neighborhoodIndex; return brandes; }; function BRANDES_DIJKSTRA_HEAP_COMPARATOR(a, b) { if (a[0] > b[0]) return 1; if (a[0] < b[0]) return -1; if (a[1] > b[1]) return 1; if (a[1] < b[1]) return -1; if (a[2] > b[2]) return 1; if (a[2] < b[2]) return -1; if (a[3] > b[3]) return 1; if (a[3] < b[3]) return - 1; return 0; } /** * Indexed Dijkstra Brandes routine. * * [Reference]: * Ulrik Brandes: A Faster Algorithm for Betweenness Centrality. * Journal of Mathematical Sociology 25(2):163-177, 2001. * * @param {Graph} graph - The graphology instance. * @param {string} weightAttribute - Name of the weight attribute. * @return {function} */ exports.createDijkstraIndexedBrandes = function createDijkstraIndexedBrandes(graph, weightAttribute) { var neighborhoodIndex = new WeightedOutboundNeighborhoodIndex(graph, weightAttribute); var neighborhood = neighborhoodIndex.neighborhood, weights = neighborhoodIndex.weights, starts = neighborhoodIndex.starts; var order = graph.order; var S = new FixedStack(typed.getPointerArray(order), order), sigma = new Uint32Array(order), P = new Array(order), D = new Float64Array(order), seen = new Float64Array(order); // TODO: use fixed-size heap var Q = new Heap(BRANDES_DIJKSTRA_HEAP_COMPARATOR); var brandes = function(sourceIndex) { var start, stop, item, dist, pred, cost, j, v, w; var count = 0; for (v = 0; v < order; v++) { P[v] = []; sigma[v] = 0; D[v] = -1; seen[v] = -1; } sigma[sourceIndex] = 1; seen[sourceIndex] = 0; Q.push([0, count++, sourceIndex, sourceIndex]); while (Q.size !== 0) { item = Q.pop(); dist = item[0]; pred = item[2]; v = item[3]; if (D[v] !== -1) continue; S.push(v); D[v] = dist; sigma[v] += sigma[pred]; start = starts[v]; stop = starts[v + 1]; for (j = start; j < stop; j++) { w = neighborhood[j]; cost = dist + weights[j]; if (D[w] === -1 && (seen[w] === -1 || cost < seen[w])) { seen[w] = cost; Q.push([cost, count++, v, w]); sigma[w] = 0; P[w] = [v]; } else if (cost === seen[w]) { sigma[w] += sigma[v]; P[w].push(v); } } } return [S, P, sigma]; }; brandes.index = neighborhoodIndex; return brandes; }; },{"graphology-indices/neighborhood/outbound":72,"mnemonist/fixed-deque":98,"mnemonist/fixed-stack":99,"mnemonist/heap":100,"mnemonist/utils/typed-arrays":104}],98:[function(require,module,exports){ /** * Mnemonist FixedDeque * ===================== * * Fixed capacity double-ended queue implemented as ring deque. */ var iterables = require('./utils/iterables.js'), Iterator = require('obliterator/iterator'); /** * FixedDeque. * * @constructor */ function FixedDeque(ArrayClass, capacity) { if (arguments.length < 2) throw new Error('mnemonist/fixed-deque: expecting an Array class and a capacity.'); if (typeof capacity !== 'number' || capacity <= 0) throw new Error('mnemonist/fixed-deque: `capacity` should be a positive number.'); this.ArrayClass = ArrayClass; this.capacity = capacity; this.items = new ArrayClass(this.capacity); this.clear(); } /** * Method used to clear the structure. * * @return {undefined} */ FixedDeque.prototype.clear = function() { // Properties this.start = 0; this.size = 0; }; /** * Method used to append a value to the deque. * * @param {any} item - Item to append. * @return {number} - Returns the new size of the deque. */ FixedDeque.prototype.push = function(item) { if (this.size === this.capacity) throw new Error('mnemonist/fixed-deque.push: deque capacity (' + this.capacity + ') exceeded!'); var index = (this.start + this.size) % this.capacity; this.items[index] = item; return ++this.size; }; /** * Method used to prepend a value to the deque. * * @param {any} item - Item to prepend. * @return {number} - Returns the new size of the deque. */ FixedDeque.prototype.unshift = function(item) { if (this.size === this.capacity) throw new Error('mnemonist/fixed-deque.unshift: deque capacity (' + this.capacity + ') exceeded!'); var index = this.start - 1; if (this.start === 0) index = this.capacity - 1; this.items[index] = item; this.start = index; return ++this.size; }; /** * Method used to pop the deque. * * @return {any} - Returns the popped item. */ FixedDeque.prototype.pop = function() { if (this.size === 0) return; const index = (this.start + this.size - 1) % this.capacity; this.size--; return this.items[index]; }; /** * Method used to shift the deque. * * @return {any} - Returns the shifted item. */ FixedDeque.prototype.shift = function() { if (this.size === 0) return; var index = this.start; this.size--; this.start++; if (this.start === this.capacity) this.start = 0; return this.items[index]; }; /** * Method used to peek the first value of the deque. * * @return {any} */ FixedDeque.prototype.peekFirst = function() { if (this.size === 0) return; return this.items[this.start]; }; /** * Method used to peek the last value of the deque. * * @return {any} */ FixedDeque.prototype.peekLast = function() { if (this.size === 0) return; var index = this.start + this.size - 1; if (index > this.capacity) index -= this.capacity; return this.items[index]; }; /** * Method used to get the desired value of the deque. * * @param {number} index * @return {any} */ FixedDeque.prototype.get = function(index) { if (this.size === 0) return; index = this.start + index; if (index > this.capacity) index -= this.capacity; return this.items[index]; }; /** * Method used to iterate over the deque. * * @param {function} callback - Function to call for each item. * @param {object} scope - Optional scope. * @return {undefined} */ FixedDeque.prototype.forEach = function(callback, scope) { scope = arguments.length > 1 ? scope : this; var c = this.capacity, l = this.size, i = this.start, j = 0; while (j < l) { callback.call(scope, this.items[i], j, this); i++; j++; if (i === c) i = 0; } }; /** * Method used to convert the deque to a JavaScript array. * * @return {array} */ // TODO: optional array class as argument? FixedDeque.prototype.toArray = function() { // Optimization var offset = this.start + this.size; if (offset < this.capacity) return this.items.slice(this.start, offset); var array = new this.ArrayClass(this.size), c = this.capacity, l = this.size, i = this.start, j = 0; while (j < l) { array[j] = this.items[i]; i++; j++; if (i === c) i = 0; } return array; }; /** * Method used to create an iterator over the deque's values. * * @return {Iterator} */ FixedDeque.prototype.values = function() { var items = this.items, c = this.capacity, l = this.size, i = this.start, j = 0; return new Iterator(function() { if (j >= l) return { done: true }; var value = items[i]; i++; j++; if (i === c) i = 0; return { value: value, done: false }; }); }; /** * Method used to create an iterator over the deque's entries. * * @return {Iterator} */ FixedDeque.prototype.entries = function() { var items = this.items, c = this.capacity, l = this.size, i = this.start, j = 0; return new Iterator(function() { if (j >= l) return { done: true }; var value = items[i]; i++; if (i === c) i = 0; return { value: [j++, value], done: false }; }); }; /** * Attaching the #.values method to Symbol.iterator if possible. */ if (typeof Symbol !== 'undefined') FixedDeque.prototype[Symbol.iterator] = FixedDeque.prototype.values; /** * Convenience known methods. */ FixedDeque.prototype.inspect = function() { var array = this.toArray(); array.type = this.ArrayClass.name; array.capacity = this.capacity; // Trick so that node displays the name of the constructor Object.defineProperty(array, 'constructor', { value: FixedDeque, enumerable: false }); return array; }; if (typeof Symbol !== 'undefined') FixedDeque.prototype[Symbol.for('nodejs.util.inspect.custom')] = FixedDeque.prototype.inspect; /** * Static @.from function taking an abitrary iterable & converting it into * a deque. * * @param {Iterable} iterable - Target iterable. * @param {function} ArrayClass - Array class to use. * @param {number} capacity - Desired capacity. * @return {FiniteStack} */ FixedDeque.from = function(iterable, ArrayClass, capacity) { if (arguments.length < 3) { capacity = iterables.guessLength(iterable); if (typeof capacity !== 'number') throw new Error('mnemonist/fixed-deque.from: could not guess iterable length. Please provide desired capacity as last argument.'); } var deque = new FixedDeque(ArrayClass, capacity); if (iterables.isArrayLike(iterable)) { var i, l; for (i = 0, l = iterable.length; i < l; i++) deque.items[i] = iterable[i]; deque.size = l; return deque; } iterables.forEach(iterable, function(value) { deque.push(value); }); return deque; }; /** * Exporting. */ module.exports = FixedDeque; },{"./utils/iterables.js":103,"obliterator/iterator":375}],99:[function(require,module,exports){ /** * Mnemonist FixedStack * ===================== * * The fixed stack is a stack whose capacity is defined beforehand and that * cannot be exceeded. This class is really useful when combined with * byte arrays to save up some memory and avoid memory re-allocation, hence * speeding up computations. * * This has however a downside: you need to know the maximum size you stack * can have during your iteration (which is not too difficult to compute when * performing, say, a DFS on a balanced binary tree). */ var Iterator = require('obliterator/iterator'), iterables = require('./utils/iterables.js'); /** * FixedStack * * @constructor * @param {function} ArrayClass - Array class to use. * @param {number} capacity - Desired capacity. */ function FixedStack(ArrayClass, capacity) { if (arguments.length < 2) throw new Error('mnemonist/fixed-stack: expecting an Array class and a capacity.'); if (typeof capacity !== 'number' || capacity <= 0) throw new Error('mnemonist/fixed-stack: `capacity` should be a positive number.'); this.capacity = capacity; this.ArrayClass = ArrayClass; this.items = new this.ArrayClass(this.capacity); this.clear(); } /** * Method used to clear the stack. * * @return {undefined} */ FixedStack.prototype.clear = function() { // Properties this.size = 0; }; /** * Method used to add an item to the stack. * * @param {any} item - Item to add. * @return {number} */ FixedStack.prototype.push = function(item) { if (this.size === this.capacity) throw new Error('mnemonist/fixed-stack.push: stack capacity (' + this.capacity + ') exceeded!'); this.items[this.size++] = item; return this.size; }; /** * Method used to retrieve & remove the last item of the stack. * * @return {any} */ FixedStack.prototype.pop = function() { if (this.size === 0) return; return this.items[--this.size]; }; /** * Method used to get the last item of the stack. * * @return {any} */ FixedStack.prototype.peek = function() { return this.items[this.size - 1]; }; /** * Method used to iterate over the stack. * * @param {function} callback - Function to call for each item. * @param {object} scope - Optional scope. * @return {undefined} */ FixedStack.prototype.forEach = function(callback, scope) { scope = arguments.length > 1 ? scope : this; for (var i = 0, l = this.items.length; i < l; i++) callback.call(scope, this.items[l - i - 1], i, this); }; /** * Method used to convert the stack to a JavaScript array. * * @return {array} */ FixedStack.prototype.toArray = function() { var array = new this.ArrayClass(this.size), l = this.size - 1, i = this.size; while (i--) array[i] = this.items[l - i]; return array; }; /** * Method used to create an iterator over a stack's values. * * @return {Iterator} */ FixedStack.prototype.values = function() { var items = this.items, l = this.size, i = 0; return new Iterator(function() { if (i >= l) return { done: true }; var value = items[l - i - 1]; i++; return { value: value, done: false }; }); }; /** * Method used to create an iterator over a stack's entries. * * @return {Iterator} */ FixedStack.prototype.entries = function() { var items = this.items, l = this.size, i = 0; return new Iterator(function() { if (i >= l) return { done: true }; var value = items[l - i - 1]; return { value: [i++, value], done: false }; }); }; /** * Attaching the #.values method to Symbol.iterator if possible. */ if (typeof Symbol !== 'undefined') FixedStack.prototype[Symbol.iterator] = FixedStack.prototype.values; /** * Convenience known methods. */ FixedStack.prototype.toString = function() { return this.toArray().join(','); }; FixedStack.prototype.toJSON = function() { return this.toArray(); }; FixedStack.prototype.inspect = function() { var array = this.toArray(); array.type = this.ArrayClass.name; array.capacity = this.capacity; // Trick so that node displays the name of the constructor Object.defineProperty(array, 'constructor', { value: FixedStack, enumerable: false }); return array; }; if (typeof Symbol !== 'undefined') FixedStack.prototype[Symbol.for('nodejs.util.inspect.custom')] = FixedStack.prototype.inspect; /** * Static @.from function taking an abitrary iterable & converting it into * a stack. * * @param {Iterable} iterable - Target iterable. * @param {function} ArrayClass - Array class to use. * @param {number} capacity - Desired capacity. * @return {FixedStack} */ FixedStack.from = function(iterable, ArrayClass, capacity) { if (arguments.length < 3) { capacity = iterables.guessLength(iterable); if (typeof capacity !== 'number') throw new Error('mnemonist/fixed-stack.from: could not guess iterable length. Please provide desired capacity as last argument.'); } var stack = new FixedStack(ArrayClass, capacity); if (iterables.isArrayLike(iterable)) { var i, l; for (i = 0, l = iterable.length; i < l; i++) stack.items[i] = iterable[i]; stack.size = l; return stack; } iterables.forEach(iterable, function(value) { stack.push(value); }); return stack; }; /** * Exporting. */ module.exports = FixedStack; },{"./utils/iterables.js":103,"obliterator/iterator":375}],100:[function(require,module,exports){ /** * Mnemonist Binary Heap * ====================== * * Binary heap implementation. */ var forEach = require('obliterator/foreach'), comparators = require('./utils/comparators.js'), iterables = require('./utils/iterables.js'); var DEFAULT_COMPARATOR = comparators.DEFAULT_COMPARATOR, reverseComparator = comparators.reverseComparator; /** * Heap helper functions. */ /** * Function used to sift down. * * @param {function} compare - Comparison function. * @param {array} heap - Array storing the heap's data. * @param {number} startIndex - Starting index. * @param {number} i - Index. */ function siftDown(compare, heap, startIndex, i) { var item = heap[i], parentIndex, parent; while (i > startIndex) { parentIndex = (i - 1) >> 1; parent = heap[parentIndex]; if (compare(item, parent) < 0) { heap[i] = parent; i = parentIndex; continue; } break; } heap[i] = item; } /** * Function used to sift up. * * @param {function} compare - Comparison function. * @param {array} heap - Array storing the heap's data. * @param {number} i - Index. */ function siftUp(compare, heap, i) { var endIndex = heap.length, startIndex = i, item = heap[i], childIndex = 2 * i + 1, rightIndex; while (childIndex < endIndex) { rightIndex = childIndex + 1; if ( rightIndex < endIndex && compare(heap[childIndex], heap[rightIndex]) >= 0 ) { childIndex = rightIndex; } heap[i] = heap[childIndex]; i = childIndex; childIndex = 2 * i + 1; } heap[i] = item; siftDown(compare, heap, startIndex, i); } /** * Function used to push an item into a heap represented by a raw array. * * @param {function} compare - Comparison function. * @param {array} heap - Array storing the heap's data. * @param {any} item - Item to push. */ function push(compare, heap, item) { heap.push(item); siftDown(compare, heap, 0, heap.length - 1); } /** * Function used to pop an item from a heap represented by a raw array. * * @param {function} compare - Comparison function. * @param {array} heap - Array storing the heap's data. * @return {any} */ function pop(compare, heap) { var lastItem = heap.pop(); if (heap.length !== 0) { var item = heap[0]; heap[0] = lastItem; siftUp(compare, heap, 0); return item; } return lastItem; } /** * Function used to pop the heap then push a new value into it, thus "replacing" * it. * * @param {function} compare - Comparison function. * @param {array} heap - Array storing the heap's data. * @param {any} item - The item to push. * @return {any} */ function replace(compare, heap, item) { if (heap.length === 0) throw new Error('mnemonist/heap.replace: cannot pop an empty heap.'); var popped = heap[0]; heap[0] = item; siftUp(compare, heap, 0); return popped; } /** * Function used to push an item in the heap then pop the heap and return the * popped value. * * @param {function} compare - Comparison function. * @param {array} heap - Array storing the heap's data. * @param {any} item - The item to push. * @return {any} */ function pushpop(compare, heap, item) { var tmp; if (heap.length !== 0 && compare(heap[0], item) < 0) { tmp = heap[0]; heap[0] = item; item = tmp; siftUp(compare, heap, 0); } return item; } /** * Converts and array into an abstract heap in linear time. * * @param {function} compare - Comparison function. * @param {array} array - Target array. */ function heapify(compare, array) { var n = array.length, l = n >> 1, i = l; while (--i >= 0) siftUp(compare, array, i); } /** * Fully consumes the given heap. * * @param {function} compare - Comparison function. * @param {array} heap - Array storing the heap's data. * @return {array} */ function consume(compare, heap) { var l = heap.length, i = 0; var array = new Array(l); while (i < l) array[i++] = pop(compare, heap); return array; } /** * Function used to retrieve the n smallest items from the given iterable. * * @param {function} compare - Comparison function. * @param {number} n - Number of top items to retrieve. * @param {any} iterable - Arbitrary iterable. * @param {array} */ function nsmallest(compare, n, iterable) { if (arguments.length === 2) { iterable = n; n = compare; compare = DEFAULT_COMPARATOR; } var reverseCompare = reverseComparator(compare); var i, l, v; var min = Infinity; var result; // If n is equal to 1, it's just a matter of finding the minimum if (n === 1) { if (iterables.isArrayLike(iterable)) { for (i = 0, l = iterable.length; i < l; i++) { v = iterable[i]; if (min === Infinity || compare(v, min) < 0) min = v; } result = new iterable.constructor(1); result[0] = min; return result; } forEach(iterable, function(value) { if (min === Infinity || compare(value, min) < 0) min = value; }); return [min]; } if (iterables.isArrayLike(iterable)) { // If n > iterable length, we just clone and sort if (n >= iterable.length) return iterable.slice().sort(compare); result = iterable.slice(0, n); heapify(reverseCompare, result); for (i = n, l = iterable.length; i < l; i++) if (reverseCompare(iterable[i], result[0]) > 0) replace(reverseCompare, result, iterable[i]); // NOTE: if n is over some number, it becomes faster to consume the heap return result.sort(compare); } // Correct for size var size = iterables.guessLength(iterable); if (size !== null && size < n) n = size; result = new Array(n); i = 0; forEach(iterable, function(value) { if (i < n) { result[i] = value; } else { if (i === n) heapify(reverseCompare, result); if (reverseCompare(value, result[0]) > 0) replace(reverseCompare, result, value); } i++; }); if (result.length > i) result.length = i; // NOTE: if n is over some number, it becomes faster to consume the heap return result.sort(compare); } /** * Function used to retrieve the n largest items from the given iterable. * * @param {function} compare - Comparison function. * @param {number} n - Number of top items to retrieve. * @param {any} iterable - Arbitrary iterable. * @param {array} */ function nlargest(compare, n, iterable) { if (arguments.length === 2) { iterable = n; n = compare; compare = DEFAULT_COMPARATOR; } var reverseCompare = reverseComparator(compare); var i, l, v; var max = -Infinity; var result; // If n is equal to 1, it's just a matter of finding the maximum if (n === 1) { if (iterables.isArrayLike(iterable)) { for (i = 0, l = iterable.length; i < l; i++) { v = iterable[i]; if (max === -Infinity || compare(v, max) > 0) max = v; } result = new iterable.constructor(1); result[0] = max; return result; } forEach(iterable, function(value) { if (max === -Infinity || compare(value, max) > 0) max = value; }); return [max]; } if (iterables.isArrayLike(iterable)) { // If n > iterable length, we just clone and sort if (n >= iterable.length) return iterable.slice().sort(reverseCompare); result = iterable.slice(0, n); heapify(compare, result); for (i = n, l = iterable.length; i < l; i++) if (compare(iterable[i], result[0]) > 0) replace(compare, result, iterable[i]); // NOTE: if n is over some number, it becomes faster to consume the heap return result.sort(reverseCompare); } // Correct for size var size = iterables.guessLength(iterable); if (size !== null && size < n) n = size; result = new Array(n); i = 0; forEach(iterable, function(value) { if (i < n) { result[i] = value; } else { if (i === n) heapify(compare, result); if (compare(value, result[0]) > 0) replace(compare, result, value); } i++; }); if (result.length > i) result.length = i; // NOTE: if n is over some number, it becomes faster to consume the heap return result.sort(reverseCompare); } /** * Binary Minimum Heap. * * @constructor * @param {function} comparator - Comparator function to use. */ function Heap(comparator) { this.clear(); this.comparator = comparator || DEFAULT_COMPARATOR; if (typeof this.comparator !== 'function') throw new Error('mnemonist/Heap.constructor: given comparator should be a function.'); } /** * Method used to clear the heap. * * @return {undefined} */ Heap.prototype.clear = function() { // Properties this.items = []; this.size = 0; }; /** * Method used to push an item into the heap. * * @param {any} item - Item to push. * @return {number} */ Heap.prototype.push = function(item) { push(this.comparator, this.items, item); return ++this.size; }; /** * Method used to retrieve the "first" item of the heap. * * @return {any} */ Heap.prototype.peek = function() { return this.items[0]; }; /** * Method used to retrieve & remove the "first" item of the heap. * * @return {any} */ Heap.prototype.pop = function() { if (this.size !== 0) this.size--; return pop(this.comparator, this.items); }; /** * Method used to pop the heap, then push an item and return the popped * item. * * @param {any} item - Item to push into the heap. * @return {any} */ Heap.prototype.replace = function(item) { return replace(this.comparator, this.items, item); }; /** * Method used to push the heap, the pop it and return the pooped item. * * @param {any} item - Item to push into the heap. * @return {any} */ Heap.prototype.pushpop = function(item) { return pushpop(this.comparator, this.items, item); }; /** * Method used to consume the heap fully and return its items as a sorted array. * * @return {array} */ Heap.prototype.consume = function() { this.size = 0; return consume(this.comparator, this.items); }; /** * Method used to convert the heap to an array. Note that it basically clone * the heap and consumes it completely. This is hardly performant. * * @return {array} */ Heap.prototype.toArray = function() { return consume(this.comparator, this.items.slice()); }; /** * Convenience known methods. */ Heap.prototype.inspect = function() { var proxy = this.toArray(); // Trick so that node displays the name of the constructor Object.defineProperty(proxy, 'constructor', { value: Heap, enumerable: false }); return proxy; }; if (typeof Symbol !== 'undefined') Heap.prototype[Symbol.for('nodejs.util.inspect.custom')] = Heap.prototype.inspect; /** * Binary Maximum Heap. * * @constructor * @param {function} comparator - Comparator function to use. */ function MaxHeap(comparator) { this.clear(); this.comparator = comparator || DEFAULT_COMPARATOR; if (typeof this.comparator !== 'function') throw new Error('mnemonist/MaxHeap.constructor: given comparator should be a function.'); this.comparator = reverseComparator(this.comparator); } MaxHeap.prototype = Heap.prototype; /** * Static @.from function taking an abitrary iterable & converting it into * a heap. * * @param {Iterable} iterable - Target iterable. * @param {function} comparator - Custom comparator function. * @return {Heap} */ Heap.from = function(iterable, comparator) { var heap = new Heap(comparator); var items; // If iterable is an array, we can be clever about it if (iterables.isArrayLike(iterable)) items = iterable.slice(); else items = iterables.toArray(iterable); heapify(heap.comparator, items); heap.items = items; heap.size = items.length; return heap; }; MaxHeap.from = function(iterable, comparator) { var heap = new MaxHeap(comparator); var items; // If iterable is an array, we can be clever about it if (iterables.isArrayLike(iterable)) items = iterable.slice(); else items = iterables.toArray(iterable); heapify(heap.comparator, items); heap.items = items; heap.size = items.length; return heap; }; /** * Exporting. */ Heap.siftUp = siftUp; Heap.siftDown = siftDown; Heap.push = push; Heap.pop = pop; Heap.replace = replace; Heap.pushpop = pushpop; Heap.heapify = heapify; Heap.consume = consume; Heap.nsmallest = nsmallest; Heap.nlargest = nlargest; Heap.MinHeap = Heap; Heap.MaxHeap = MaxHeap; module.exports = Heap; },{"./utils/comparators.js":102,"./utils/iterables.js":103,"obliterator/foreach":374}],101:[function(require,module,exports){ /** * Mnemonist Queue * ================ * * Queue implementation based on the ideas of Queue.js that seems to beat * a LinkedList one in performance. */ var Iterator = require('obliterator/iterator'), forEach = require('obliterator/foreach'); /** * Queue * * @constructor */ function Queue() { this.clear(); } /** * Method used to clear the queue. * * @return {undefined} */ Queue.prototype.clear = function() { // Properties this.items = []; this.offset = 0; this.size = 0; }; /** * Method used to add an item to the queue. * * @param {any} item - Item to enqueue. * @return {number} */ Queue.prototype.enqueue = function(item) { this.items.push(item); return ++this.size; }; /** * Method used to retrieve & remove the first item of the queue. * * @return {any} */ Queue.prototype.dequeue = function() { if (!this.size) return; var item = this.items[this.offset]; if (++this.offset * 2 >= this.items.length) { this.items = this.items.slice(this.offset); this.offset = 0; } this.size--; return item; }; /** * Method used to retrieve the first item of the queue. * * @return {any} */ Queue.prototype.peek = function() { if (!this.size) return; return this.items[this.offset]; }; /** * Method used to iterate over the queue. * * @param {function} callback - Function to call for each item. * @param {object} scope - Optional scope. * @return {undefined} */ Queue.prototype.forEach = function(callback, scope) { scope = arguments.length > 1 ? scope : this; for (var i = this.offset, j = 0, l = this.items.length; i < l; i++, j++) callback.call(scope, this.items[i], j, this); }; /* * Method used to convert the queue to a JavaScript array. * * @return {array} */ Queue.prototype.toArray = function() { return this.items.slice(this.offset); }; /** * Method used to create an iterator over a queue's values. * * @return {Iterator} */ Queue.prototype.values = function() { var items = this.items, i = this.offset; return new Iterator(function() { if (i >= items.length) return { done: true }; var value = items[i]; i++; return { value: value, done: false }; }); }; /** * Method used to create an iterator over a queue's entries. * * @return {Iterator} */ Queue.prototype.entries = function() { var items = this.items, i = this.offset, j = 0; return new Iterator(function() { if (i >= items.length) return { done: true }; var value = items[i]; i++; return { value: [j++, value], done: false }; }); }; /** * Attaching the #.values method to Symbol.iterator if possible. */ if (typeof Symbol !== 'undefined') Queue.prototype[Symbol.iterator] = Queue.prototype.values; /** * Convenience known methods. */ Queue.prototype.toString = function() { return this.toArray().join(','); }; Queue.prototype.toJSON = function() { return this.toArray(); }; Queue.prototype.inspect = function() { var array = this.toArray(); // Trick so that node displays the name of the constructor Object.defineProperty(array, 'constructor', { value: Queue, enumerable: false }); return array; }; if (typeof Symbol !== 'undefined') Queue.prototype[Symbol.for('nodejs.util.inspect.custom')] = Queue.prototype.inspect; /** * Static @.from function taking an abitrary iterable & converting it into * a queue. * * @param {Iterable} iterable - Target iterable. * @return {Queue} */ Queue.from = function(iterable) { var queue = new Queue(); forEach(iterable, function(value) { queue.enqueue(value); }); return queue; }; /** * Static @.of function taking an abitrary number of arguments & converting it * into a queue. * * @param {...any} args * @return {Queue} */ Queue.of = function() { return Queue.from(arguments); }; /** * Exporting. */ module.exports = Queue; },{"obliterator/foreach":374,"obliterator/iterator":375}],102:[function(require,module,exports){ /** * Mnemonist Heap Comparators * =========================== * * Default comparators & functions dealing with comparators reversing etc. */ var DEFAULT_COMPARATOR = function(a, b) { if (a < b) return -1; if (a > b) return 1; return 0; }; var DEFAULT_REVERSE_COMPARATOR = function(a, b) { if (a < b) return 1; if (a > b) return -1; return 0; }; /** * Function used to reverse a comparator. */ function reverseComparator(comparator) { return function(a, b) { return comparator(b, a); }; } /** * Function returning a tuple comparator. */ function createTupleComparator(size) { if (size === 2) { return function(a, b) { if (a[0] < b[0]) return -1; if (a[0] > b[0]) return 1; if (a[1] < b[1]) return -1; if (a[1] > b[1]) return 1; return 0; }; } return function(a, b) { var i = 0; while (i < size) { if (a[i] < b[i]) return -1; if (a[i] > b[i]) return 1; i++; } return 0; }; } /** * Exporting. */ exports.DEFAULT_COMPARATOR = DEFAULT_COMPARATOR; exports.DEFAULT_REVERSE_COMPARATOR = DEFAULT_REVERSE_COMPARATOR; exports.reverseComparator = reverseComparator; exports.createTupleComparator = createTupleComparator; },{}],103:[function(require,module,exports){ /** * Mnemonist Iterable Function * ============================ * * Harmonized iteration helpers over mixed iterable targets. */ var forEach = require('obliterator/foreach'); var isTypedArray = require('./typed-arrays.js').isTypedArray; /** * Function used to determine whether the given object supports array-like * random access. * * @param {any} target - Target object. * @return {boolean} */ function isArrayLike(target) { return Array.isArray(target) || isTypedArray(target); } /** * Function used to guess the length of the structure over which we are going * to iterate. * * @param {any} target - Target object. * @return {number|undefined} */ function guessLength(target) { if (typeof target.length === 'number') return target.length; if (typeof target.size === 'number') return target.size; return; } /** * Function used to convert an iterable to an array. * * @param {any} target - Iteration target. * @return {array} */ function toArray(target) { var l = guessLength(target); var array = typeof l === 'number' ? new Array(l) : []; var i = 0; forEach(target, function(value) { array[i++] = value; }); return array; } /** * Exporting. */ exports.isArrayLike = isArrayLike; exports.guessLength = guessLength; exports.toArray = toArray; },{"./typed-arrays.js":104,"obliterator/foreach":374}],104:[function(require,module,exports){ arguments[4][73][0].apply(exports,arguments) },{"dup":73}],105:[function(require,module,exports){ /** * Graphology Unweighted Shortest Path * ==================================== * * Basic algorithms to find the shortest paths between nodes in a graph * whose edges are not weighted. */ var isGraph = require('graphology-utils/is-graph'), Queue = require('mnemonist/queue'), extend = require('@yomguithereal/helpers/extend'); /** * Function attempting to find the shortest path in a graph between * given source & target or `null` if such a path does not exist. * * @param {Graph} graph - Target graph. * @param {any} source - Source node. * @param {any} target - Target node. * @return {array|null} - Found path or `null`. */ function bidirectional(graph, source, target) { if (!isGraph(graph)) throw new Error('graphology-shortest-path: invalid graphology instance.'); if (arguments.length < 3) throw new Error('graphology-shortest-path: invalid number of arguments. Expecting at least 3.'); if (!graph.hasNode(source)) throw new Error('graphology-shortest-path: the "' + source + '" source node does not exist in the given graph.'); if (!graph.hasNode(target)) throw new Error('graphology-shortest-path: the "' + target + '" target node does not exist in the given graph.'); source = '' + source; target = '' + target; // TODO: do we need a self loop to go there? if (source === target) { return [source]; } // Binding functions var getPredecessors = graph.inboundNeighbors.bind(graph), getSuccessors = graph.outboundNeighbors.bind(graph); var predecessor = {}, successor = {}; // Predecessor & successor predecessor[source] = null; successor[target] = null; // Fringes var forwardFringe = [source], reverseFringe = [target], currentFringe, node, neighbors, neighbor, i, j, l, m; var found = false; outer: while (forwardFringe.length && reverseFringe.length) { if (forwardFringe.length <= reverseFringe.length) { currentFringe = forwardFringe; forwardFringe = []; for (i = 0, l = currentFringe.length; i < l; i++) { node = currentFringe[i]; neighbors = getSuccessors(node); for (j = 0, m = neighbors.length; j < m; j++) { neighbor = neighbors[j]; if (!(neighbor in predecessor)) { forwardFringe.push(neighbor); predecessor[neighbor] = node; } if (neighbor in successor) { // Path is found! found = true; break outer; } } } } else { currentFringe = reverseFringe; reverseFringe = []; for (i = 0, l = currentFringe.length; i < l; i++) { node = currentFringe[i]; neighbors = getPredecessors(node); for (j = 0, m = neighbors.length; j < m; j++) { neighbor = neighbors[j]; if (!(neighbor in successor)) { reverseFringe.push(neighbor); successor[neighbor] = node; } if (neighbor in predecessor) { // Path is found! found = true; break outer; } } } } } if (!found) return null; var path = []; while (neighbor) { path.unshift(neighbor); neighbor = predecessor[neighbor]; } neighbor = successor[path[path.length - 1]]; while (neighbor) { path.push(neighbor); neighbor = successor[neighbor]; } return path.length ? path : null; } /** * Function attempting to find the shortest path in the graph between the * given source node & all the other nodes. * * @param {Graph} graph - Target graph. * @param {any} source - Source node. * @return {object} - The map of found paths. */ // TODO: cutoff option function singleSource(graph, source) { if (!isGraph(graph)) throw new Error('graphology-shortest-path: invalid graphology instance.'); if (arguments.length < 2) throw new Error('graphology-shortest-path: invalid number of arguments. Expecting at least 2.'); if (!graph.hasNode(source)) throw new Error('graphology-shortest-path: the "' + source + '" source node does not exist in the given graph.'); source = '' + source; var nextLevel = {}, paths = {}, currentLevel, neighbors, v, w, i, l; nextLevel[source] = true; paths[source] = [source]; while (Object.keys(nextLevel).length) { currentLevel = nextLevel; nextLevel = {}; for (v in currentLevel) { neighbors = graph.outboundNeighbors(v); for (i = 0, l = neighbors.length; i < l; i++) { w = neighbors[i]; if (!paths[w]) { paths[w] = paths[v].concat(w); nextLevel[w] = true; } } } } return paths; } /** * Function attempting to find the shortest path lengths in the graph between * the given source node & all the other nodes. * * @param {string} method - Neighbor collection method name. * @param {Graph} graph - Target graph. * @param {any} source - Source node. * @return {object} - The map of found path lengths. */ // TODO: cutoff option function asbtractSingleSourceLength(method, graph, source) { if (!isGraph(graph)) throw new Error('graphology-shortest-path: invalid graphology instance.'); if (!graph.hasNode(source)) throw new Error('graphology-shortest-path: the "' + source + '" source node does not exist in the given graph.'); source = '' + source; // Performing BFS to count shortest paths var seen = new Set(); var lengths = {}, level = 0; lengths[source] = 0; var currentLevel = [source]; var i, l, node; while (currentLevel.length !== 0) { var nextLevel = []; for (i = 0, l = currentLevel.length; i < l; i++) { node = currentLevel[i]; if (seen.has(node)) continue; seen.add(node); extend(nextLevel, graph[method](node)); lengths[node] = level; } level++; currentLevel = nextLevel; } return lengths; } var singleSourceLength = asbtractSingleSourceLength.bind(null, 'outboundNeighbors'); var undirectedSingleSourceLength = asbtractSingleSourceLength.bind(null, 'neighbors'); /** * Main polymorphic function taking either only a source or a * source/target combo. * * @param {Graph} graph - Target graph. * @param {any} source - Source node. * @param {any} [target] - Target node. * @return {array|object|null} - The map of found paths. */ function shortestPath(graph, source, target) { if (arguments.length < 3) return singleSource(graph, source); return bidirectional(graph, source, target); } /** * Function using Ulrik Brandes' method to map single source shortest paths * from selected node. * * [Reference]: * Ulrik Brandes: A Faster Algorithm for Betweenness Centrality. * Journal of Mathematical Sociology 25(2):163-177, 2001. * * @param {Graph} graph - Target graph. * @param {any} source - Source node. * @return {array} - [Stack, Paths, Sigma] */ function brandes(graph, source) { source = '' + source; var S = [], P = {}, sigma = {}; var nodes = graph.nodes(), Dv, sigmav, neighbors, v, w, i, j, l, m; for (i = 0, l = nodes.length; i < l; i++) { v = nodes[i]; P[v] = []; sigma[v] = 0; } var D = {}; sigma[source] = 1; D[source] = 0; var queue = Queue.of(source); while (queue.size) { v = queue.dequeue(); S.push(v); Dv = D[v]; sigmav = sigma[v]; neighbors = graph.outboundNeighbors(v); for (j = 0, m = neighbors.length; j < m; j++) { w = neighbors[j]; if (!(w in D)) { queue.enqueue(w); D[w] = Dv + 1; } if (D[w] === Dv + 1) { sigma[w] += sigmav; P[w].push(v); } } } return [S, P, sigma]; } /** * Exporting. */ shortestPath.bidirectional = bidirectional; shortestPath.singleSource = singleSource; shortestPath.singleSourceLength = singleSourceLength; shortestPath.undirectedSingleSourceLength = undirectedSingleSourceLength; shortestPath.brandes = brandes; module.exports = shortestPath; },{"@yomguithereal/helpers/extend":40,"graphology-utils/is-graph":108,"mnemonist/queue":101}],106:[function(require,module,exports){ /** * Graphology inferType * ===================== * * Useful function used to "guess" the real type of the given Graph using * introspection. */ var isGraph = require('./is-graph.js'); /** * Returning the inferred type of the given graph. * * @param {Graph} graph - Target graph. * @return {boolean} */ module.exports = function inferType(graph) { if (!isGraph(graph)) throw new Error('graphology-utils/infer-type: expecting a valid graphology instance.'); var declaredType = graph.type; if (declaredType !== 'mixed') return declaredType; if ( (graph.directedSize === 0 && graph.undirectedSize === 0) || (graph.directedSize > 0 && graph.undirectedSize > 0) ) return 'mixed'; if (graph.directedSize > 0) return 'directed'; return 'undirected'; }; },{"./is-graph.js":108}],107:[function(require,module,exports){ /** * Graphology isGraphConstructor * ============================== * * Very simple function aiming at ensuring the given variable is a * graphology constructor. */ /** * Checking the value is a graphology constructor. * * @param {any} value - Target value. * @return {boolean} */ module.exports = function isGraphConstructor(value) { return ( value !== null && typeof value === 'function' && typeof value.prototype === 'object' && typeof value.prototype.addUndirectedEdgeWithKey === 'function' && typeof value.prototype.dropNode === 'function' ); }; },{}],108:[function(require,module,exports){ /** * Graphology isGraph * =================== * * Very simple function aiming at ensuring the given variable is a * graphology instance. */ /** * Checking the value is a graphology instance. * * @param {any} value - Target value. * @return {boolean} */ module.exports = function isGraph(value) { return ( value !== null && typeof value === 'object' && typeof value.addUndirectedEdgeWithKey === 'function' && typeof value.dropNode === 'function' && typeof value.multi === 'boolean' ); }; },{}],109:[function(require,module,exports){ /** * Graphology mergePath * ===================== * * Function merging the given path to the graph. */ /** * Merging the given path to the graph. * * @param {Graph} graph - Target graph. * @param {array} nodes - Nodes representing the path to merge. */ module.exports = function mergePath(graph, nodes) { if (nodes.length === 0) return; var previousNode, node, i, l; graph.mergeNode(nodes[0]); for (i = 1, l = nodes.length; i < l; i++) { previousNode = nodes[i - 1]; node = nodes[i]; graph.mergeEdge(previousNode, node); } }; },{}],110:[function(require,module,exports){ /** * Graphology Sub Graph * ===================== * * Function returning the subgraph composed of the nodes passed as parameters. */ /** * Returning the subgraph composed of the nodes passed as parameters. * * @param {Graph} graph - Graph containing the subgraph. * @param {array} nodes - Array, set or function defining the nodes wanted in the subgraph. */ module.exports = function subGraph(graph, nodes) { var nodesSet; var subGraphResult = graph.nullCopy(); if (Array.isArray(nodes)) { nodesSet = new Set(nodes); } else if (nodes instanceof Set) { nodesSet = nodes; } else if (typeof nodes === 'function') { nodesSet = new Set(); graph.forEachNode(function(key, attrs) { if (nodes(key, attrs)) { nodesSet.add(key); } }); } else { throw new Error( 'The argument "nodes" is neither an array, nor a set, nor a function.' ); } if (nodesSet.size === 0) return subGraphResult; var insertedSelfloops = new Set(); // Useful to check if a selfloop has already been inserted or not nodesSet.forEach(function(node) { // Nodes addition if (!graph.hasNode(node)) throw new Error('graphology-utils/subgraph: the "' + node + '" node is not present in the graph.'); subGraphResult.addNode(node, graph.getNodeAttributes(node)); }); nodesSet.forEach(function(node) { // Edges addition graph.forEachOutEdge(node, function(edge, attributes, source, target) { if (nodesSet.has(target)) { subGraphResult.importEdge(graph.exportEdge(edge)); } }); graph.forEachUndirectedEdge(node, function( edge, attributes, source, target ) { if (source !== node) { var tmp = source; source = target; target = tmp; } if (nodesSet.has(target)) { if (source === target && !insertedSelfloops.has(edge)) { subGraphResult.importEdge(graph.exportEdge(edge)); insertedSelfloops.add(edge); } else if (source > target) { subGraphResult.importEdge(graph.exportEdge(edge)); } } }); }); return subGraphResult; }; },{}],111:[function(require,module,exports){ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).graphology=t()}(this,(function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function n(e){return(n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function r(e,t){return(r=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function i(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function o(e,t,n){return(o=i()?Reflect.construct:function(e,t,n){var i=[null];i.push.apply(i,t);var o=new(Function.bind.apply(e,i));return n&&r(o,n.prototype),o}).apply(null,arguments)}function a(e){var t="function"==typeof Map?new Map:void 0;return(a=function(e){if(null===e||(i=e,-1===Function.toString.call(i).indexOf("[native code]")))return e;var i;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,a)}function a(){return o(e,arguments,n(this).constructor)}return a.prototype=Object.create(e.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),r(a,e)})(e)}function c(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function d(){for(var e=arguments[0]||{},t=1,n=arguments.length;t0&&a.length>i){a.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=a.length,c=d,"function"==typeof console.warn?console.warn(c):console.log(c)}}else a=o[t]=n,++e._eventsCount;return e}function k(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}function x(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function S(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}function A(e){Object.defineProperty(this,"_next",{writable:!1,enumerable:!1,value:e}),this.done=!1}l.prototype=Object.create(null),y.EventEmitter=y,y.usingDomains=!1,y.prototype.domain=void 0,y.prototype._events=void 0,y.prototype._maxListeners=void 0,y.defaultMaxListeners=10,y.init=function(){this.domain=null,y.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new l,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},y.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},y.prototype.getMaxListeners=function(){return v(this)},y.prototype.emit=function(e){var t,n,r,i,o,a,c,d="error"===e;if(a=this._events)d=d&&null==a.error;else if(!d)return!1;if(c=this.domain,d){if(t=arguments[1],!c){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=c,t.domainThrown=!1,c.emit("error",t),!1}if(!(n=a[e]))return!1;var s="function"==typeof n;switch(r=arguments.length){case 1:w(n,s,this);break;case 2:b(n,s,this,arguments[1]);break;case 3:m(n,s,this,arguments[1],arguments[2]);break;case 4:_(n,s,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(r-1),o=1;o0;)if(n[o]===t||n[o].listener&&n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new l,this;delete r[e]}else!function(e,t){for(var n=t,r=n+1,i=e.length;r0?Reflect.ownKeys(this._events):[]},A.prototype.next=function(){if(this.done)return{done:!0};var e=this._next();return e.done&&(this.done=!0),e},"undefined"!=typeof Symbol&&(A.prototype[Symbol.iterator]=function(){return this}),A.of=function(){var e=arguments,t=e.length,n=0;return new A((function(){return n>=t?{done:!0}:{done:!1,value:e[n++]}}))},A.empty=function(){var e=new A(null);return e.done=!0,e},A.is=function(e){return e instanceof A||"object"==typeof e&&null!==e&&"function"==typeof e.next};var N=A,D=function(e,t){for(var n,r=arguments.length>1?t:1/0,i=r!==1/0?new Array(r):[],o=0;;){if(o===r)return i;if((n=e.next()).done)return o!==t?i.slice(0,o):i;i[o++]=n.value}},L=function(e){function n(t,n){var r;return(r=e.call(this)||this).name="GraphError",r.message=t||"",r.data=n||{},r}return t(n,e),n}(a(Error)),j=function(e){function n(t,r){var i;return(i=e.call(this,t,r)||this).name="InvalidArgumentsGraphError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(c(i),n.prototype.constructor),i}return t(n,e),n}(L),U=function(e){function n(t,r){var i;return(i=e.call(this,t,r)||this).name="NotFoundGraphError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(c(i),n.prototype.constructor),i}return t(n,e),n}(L),z=function(e){function n(t,r){var i;return(i=e.call(this,t,r)||this).name="UsageGraphError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(c(i),n.prototype.constructor),i}return t(n,e),n}(L);function O(e,t){this.key=e,this.attributes=t,this.inDegree=0,this.outDegree=0,this.undirectedDegree=0,this.directedSelfLoops=0,this.undirectedSelfLoops=0,this.in={},this.out={},this.undirected={}}function K(e,t){this.key=e,this.attributes=t||{},this.inDegree=0,this.outDegree=0,this.directedSelfLoops=0,this.in={},this.out={}}function M(e,t){this.key=e,this.attributes=t||{},this.undirectedDegree=0,this.undirectedSelfLoops=0,this.undirected={}}function C(e,t,n,r,i){this.key=e,this.attributes=i,this.source=n,this.target=r,this.generatedKey=t}function T(e,t,n,r,i){this.key=e,this.attributes=i,this.source=n,this.target=r,this.generatedKey=t}function P(e,t,n,r,i,o,a){var c=e.multi,d=t?"undirected":"out",u=t?"undirected":"in",s=o[d][i];void 0===s&&(s=c?new Set:n,o[d][i]=s),c&&s.add(n),r!==i&&void 0===a[u][r]&&(a[u][r]=s)}function W(e,t,n){var r=e.multi,i=n.source,o=n.target,a=i.key,c=o.key,d=i[t?"undirected":"out"],u=t?"undirected":"in";if(c in d)if(r){var s=d[c];1===s.size?(delete d[c],delete o[u][a]):s.delete(n)}else delete d[c];r||delete o[u][a]}K.prototype.upgradeToMixed=function(){this.undirectedDegree=0,this.undirectedSelfLoops=0,this.undirected={}},M.prototype.upgradeToMixed=function(){this.inDegree=0,this.outDegree=0,this.directedSelfLoops=0,this.in={},this.out={}};var R=[{name:function(e){return"get".concat(e,"Attribute")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new z("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new z("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var a=""+e,c=""+i;if(i=arguments[2],!(o=u(this,a,c,n)))throw new U("Graph.".concat(t,': could not find an edge for the given path ("').concat(a,'" - "').concat(c,'").'))}else if(e=""+e,!(o=this._edges.get(e)))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'));if("mixed"!==n&&!(o instanceof r))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" ').concat(n," edge in the graph."));return o.attributes[i]}}},{name:function(e){return"get".concat(e,"Attributes")},attacher:function(e,t,n,r){e.prototype[t]=function(e){var i;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new z("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>1){if(this.multi)throw new z("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var o=""+e,a=""+arguments[1];if(!(i=u(this,o,a,n)))throw new U("Graph.".concat(t,': could not find an edge for the given path ("').concat(o,'" - "').concat(a,'").'))}else if(e=""+e,!(i=this._edges.get(e)))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'));if("mixed"!==n&&!(i instanceof r))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" ').concat(n," edge in the graph."));return i.attributes}}},{name:function(e){return"has".concat(e,"Attribute")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new z("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new z("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var a=""+e,c=""+i;if(i=arguments[2],!(o=u(this,a,c,n)))throw new U("Graph.".concat(t,': could not find an edge for the given path ("').concat(a,'" - "').concat(c,'").'))}else if(e=""+e,!(o=this._edges.get(e)))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'));if("mixed"!==n&&!(o instanceof r))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" ').concat(n," edge in the graph."));return o.attributes.hasOwnProperty(i)}}},{name:function(e){return"set".concat(e,"Attribute")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i,o){var a;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new z("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>3){if(this.multi)throw new z("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var c=""+e,d=""+i;if(i=arguments[2],o=arguments[3],!(a=u(this,c,d,n)))throw new U("Graph.".concat(t,': could not find an edge for the given path ("').concat(c,'" - "').concat(d,'").'))}else if(e=""+e,!(a=this._edges.get(e)))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'));if("mixed"!==n&&!(a instanceof r))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" ').concat(n," edge in the graph."));return a.attributes[i]=o,this.emit("edgeAttributesUpdated",{key:a.key,type:"set",meta:{name:i,value:o}}),this}}},{name:function(e){return"update".concat(e,"Attribute")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i,o){var a;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new z("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>3){if(this.multi)throw new z("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var c=""+e,d=""+i;if(i=arguments[2],o=arguments[3],!(a=u(this,c,d,n)))throw new U("Graph.".concat(t,': could not find an edge for the given path ("').concat(c,'" - "').concat(d,'").'))}else if(e=""+e,!(a=this._edges.get(e)))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'));if("function"!=typeof o)throw new j("Graph.".concat(t,": updater should be a function."));if("mixed"!==n&&!(a instanceof r))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" ').concat(n," edge in the graph."));return a.attributes[i]=o(a.attributes[i]),this.emit("edgeAttributesUpdated",{key:a.key,type:"set",meta:{name:i,value:a.attributes[i]}}),this}}},{name:function(e){return"remove".concat(e,"Attribute")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new z("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new z("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var a=""+e,c=""+i;if(i=arguments[2],!(o=u(this,a,c,n)))throw new U("Graph.".concat(t,': could not find an edge for the given path ("').concat(a,'" - "').concat(c,'").'))}else if(e=""+e,!(o=this._edges.get(e)))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'));if("mixed"!==n&&!(o instanceof r))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" ').concat(n," edge in the graph."));return delete o.attributes[i],this.emit("edgeAttributesUpdated",{key:o.key,type:"remove",meta:{name:i}}),this}}},{name:function(e){return"replace".concat(e,"Attributes")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new z("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new z("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var a=""+e,c=""+i;if(i=arguments[2],!(o=u(this,a,c,n)))throw new U("Graph.".concat(t,': could not find an edge for the given path ("').concat(a,'" - "').concat(c,'").'))}else if(e=""+e,!(o=this._edges.get(e)))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'));if(!h(i))throw new j("Graph.".concat(t,": provided attributes are not a plain object."));if("mixed"!==n&&!(o instanceof r))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" ').concat(n," edge in the graph."));var d=o.attributes;return o.attributes=i,this.emit("edgeAttributesUpdated",{key:o.key,type:"replace",meta:{before:d,after:i}}),this}}},{name:function(e){return"merge".concat(e,"Attributes")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new z("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new z("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var a=""+e,c=""+i;if(i=arguments[2],!(o=u(this,a,c,n)))throw new U("Graph.".concat(t,': could not find an edge for the given path ("').concat(a,'" - "').concat(c,'").'))}else if(e=""+e,!(o=this._edges.get(e)))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'));if(!h(i))throw new j("Graph.".concat(t,": provided attributes are not a plain object."));if("mixed"!==n&&!(o instanceof r))throw new U("Graph.".concat(t,': could not find the "').concat(e,'" ').concat(n," edge in the graph."));return d(o.attributes,i),this.emit("edgeAttributesUpdated",{key:o.key,type:"merge",meta:{data:i}}),this}}}];var I=function(){var e,t=arguments,n=-1;return new N((function r(){if(!e){if(++n>=t.length)return{done:!0};e=t[n]}var i=e.next();return i.done?(e=null,r()):i}))},F=[{name:"edges",type:"mixed"},{name:"inEdges",type:"directed",direction:"in"},{name:"outEdges",type:"directed",direction:"out"},{name:"inboundEdges",type:"mixed",direction:"in"},{name:"outboundEdges",type:"mixed",direction:"out"},{name:"directedEdges",type:"directed"},{name:"undirectedEdges",type:"undirected"}];function Y(e,t){for(var n in t)t[n]instanceof Set?t[n].forEach((function(t){return e.push(t.key)})):e.push(t[n].key)}function J(e,t){for(var n in e){var r=e[n];t(r.key,r.attributes,r.source.key,r.target.key,r.source.attributes,r.target.attributes)}}function q(e,t){for(var n in e)e[n].forEach((function(e){return t(e.key,e.attributes,e.source.key,e.target.key,e.source.attributes,e.target.attributes)}))}function B(e){var t=Object.keys(e),n=t.length,r=null,i=0;return new N((function o(){var a;if(r){var c=r.next();if(c.done)return r=null,i++,o();a=c.value}else{if(i>=n)return{done:!0};var d=t[i];if((a=e[d])instanceof Set)return r=a.values(),o();i++}return{done:!1,value:[a.key,a.attributes,a.source.key,a.target.key,a.source.attributes,a.target.attributes]}}))}function H(e,t,n){n in t&&(t[n]instanceof Set?t[n].forEach((function(t){return e.push(t.key)})):e.push(t[n].key))}function Q(e,t,n){if(t in e)if(e[t]instanceof Set)e[t].forEach((function(e){return n(e.key,e.attributes,e.source.key,e.target.key,e.source.attributes,e.target.attributes)}));else{var r=e[t];n(r.key,r.attributes,r.source.key,r.target.key,r.source.attributes,r.target.attributes)}}function V(e,t){var n=e[t];if(n instanceof Set){var r=n.values();return new N((function(){var e=r.next();if(e.done)return e;var t=e.value;return{done:!1,value:[t.key,t.attributes,t.source.key,t.target.key,t.source.attributes,t.target.attributes]}}))}return N.of([n.key,n.attributes,n.source.key,n.target.key,n.source.attributes,n.target.attributes])}function X(e,t){if(0===e.size)return[];if("mixed"===t||t===e.type)return D(e._edges.keys(),e._edges.size);var n="undirected"===t?e.undirectedSize:e.directedSize,r=new Array(n),i="undirected"===t,o=0;return e._edges.forEach((function(e,t){e instanceof T===i&&(r[o++]=t)})),r}function Z(e,t,n){if(0!==e.size)if("mixed"===t||t===e.type)e._edges.forEach((function(e,t){var r=e.attributes,i=e.source,o=e.target;n(t,r,i.key,o.key,i.attributes,o.attributes)}));else{var r="undirected"===t;e._edges.forEach((function(e,t){if(e instanceof T===r){var i=e.attributes,o=e.source,a=e.target;n(t,i,o.key,a.key,o.attributes,a.attributes)}}))}}function $(e,t){return 0===e.size?N.empty():"mixed"===t?(n=e._edges.values(),new N((function(){var e=n.next();if(e.done)return e;var t=e.value;return{value:[t.key,t.attributes,t.source.key,t.target.key,t.source.attributes,t.target.attributes],done:!1}}))):(n=e._edges.values(),new N((function e(){var r=n.next();if(r.done)return r;var i=r.value;return i instanceof T==("undirected"===t)?{value:[i.key,i.attributes,i.source.key,i.target.key,i.source.attributes,i.target.attributes],done:!1}:e()})));var n}function ee(e,t,n){var r=[];return"undirected"!==e&&("out"!==t&&Y(r,n.in),"in"!==t&&Y(r,n.out)),"directed"!==e&&Y(r,n.undirected),r}function te(e,t,n,r,i){var o=e?q:J;"undirected"!==t&&("out"!==n&&o(r.in,i),"in"!==n&&o(r.out,i)),"directed"!==t&&o(r.undirected,i)}function ne(e,t,n){var r=N.empty();return"undirected"!==e&&("out"!==t&&void 0!==n.in&&(r=I(r,B(n.in))),"in"!==t&&void 0!==n.out&&(r=I(r,B(n.out)))),"directed"!==e&&void 0!==n.undirected&&(r=I(r,B(n.undirected))),r}function re(e,t,n,r){var i=[];return"undirected"!==e&&(void 0!==n.in&&"out"!==t&&H(i,n.in,r),void 0!==n.out&&"in"!==t&&H(i,n.out,r)),"directed"!==e&&void 0!==n.undirected&&H(i,n.undirected,r),i}function ie(e,t,n,r,i){"undirected"!==e&&(void 0!==n.in&&"out"!==t&&Q(n.in,r,i),void 0!==n.out&&"in"!==t&&Q(n.out,r,i)),"directed"!==e&&void 0!==n.undirected&&Q(n.undirected,r,i)}function oe(e,t,n,r){var i=N.empty();return"undirected"!==e&&(void 0!==n.in&&"out"!==t&&r in n.in&&(i=I(i,V(n.in,r))),void 0!==n.out&&"in"!==t&&r in n.out&&(i=I(i,V(n.out,r)))),"directed"!==e&&void 0!==n.undirected&&r in n.undirected&&(i=I(i,V(n.undirected,r))),i}var ae=[{name:"neighbors",type:"mixed"},{name:"inNeighbors",type:"directed",direction:"in"},{name:"outNeighbors",type:"directed",direction:"out"},{name:"inboundNeighbors",type:"mixed",direction:"in"},{name:"outboundNeighbors",type:"mixed",direction:"out"},{name:"directedNeighbors",type:"directed"},{name:"undirectedNeighbors",type:"undirected"}];function ce(e,t){if(void 0!==t)for(var n in t)e.add(n)}function de(e,t,n){if("mixed"!==e){if("undirected"===e)return Object.keys(n.undirected);if("string"==typeof t)return Object.keys(n[t])}var r=new Set;return"undirected"!==e&&("out"!==t&&ce(r,n.in),"in"!==t&&ce(r,n.out)),"directed"!==e&&ce(r,n.undirected),D(r.values(),r.size)}function ue(e,t,n){for(var r in t){var i=t[r];i instanceof Set&&(i=i.values().next().value);var o=i.source,a=i.target,c=o===e?a:o;n(c.key,c.attributes)}}function se(e,t,n,r){for(var i in n){var o=n[i];o instanceof Set&&(o=o.values().next().value);var a=o.source,c=o.target,d=a===t?c:a;e.has(d.key)||(e.add(d.key),r(d.key,d.attributes))}}function he(e,t){var n=Object.keys(t),r=n.length,i=0;return new N((function(){if(i>=r)return{done:!0};var o=t[n[i++]];o instanceof Set&&(o=o.values().next().value);var a=o.source,c=o.target,d=a===e?c:a;return{done:!1,value:[d.key,d.attributes]}}))}function fe(e,t,n){var r=Object.keys(n),i=r.length,o=0;return new N((function a(){if(o>=i)return{done:!0};var c=n[r[o++]];c instanceof Set&&(c=c.values().next().value);var d=c.source,u=c.target,s=d===t?u:d;return e.has(s.key)?a():(e.add(s.key),{done:!1,value:[s.key,s.attributes]})}))}function pe(e,t,n,r,i){var o=e._nodes.get(r);if("undirected"!==t){if("out"!==n&&void 0!==o.in)for(var a in o.in)if(a===i)return!0;if("in"!==n&&void 0!==o.out)for(var c in o.out)if(c===i)return!0}if("directed"!==t&&void 0!==o.undirected)for(var d in o.undirected)if(d===i)return!0;return!1}function ge(e,t){var n=t.name,r=t.type,i=t.direction,o="forEach"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(e,t){if("mixed"===r||"mixed"===this.type||r===this.type){e=""+e;var n=this._nodes.get(e);if(void 0===n)throw new U("Graph.".concat(o,': could not find the "').concat(e,'" node in the graph.'));!function(e,t,n,r){if("mixed"!==e){if("undirected"===e)return ue(n,n.undirected,r);if("string"==typeof t)return ue(n,n[t],r)}var i=new Set;"undirected"!==e&&("out"!==t&&se(i,n,n.in,r),"in"!==t&&se(i,n,n.out,r)),"directed"!==e&&se(i,n,n.undirected,r)}("mixed"===r?this.type:r,i,n,t)}}}function le(e,t){var n=t.name,r=t.type,i=t.direction,o=n.slice(0,-1)+"Entries";e.prototype[o]=function(e){if("mixed"!==r&&"mixed"!==this.type&&r!==this.type)return N.empty();e=""+e;var t=this._nodes.get(e);if(void 0===t)throw new U("Graph.".concat(o,': could not find the "').concat(e,'" node in the graph.'));return function(e,t,n){if("mixed"!==e){if("undirected"===e)return he(n,n.undirected);if("string"==typeof t)return he(n,n[t])}var r=N.empty(),i=new Set;return"undirected"!==e&&("out"!==t&&(r=I(r,fe(i,n,n.in))),"in"!==t&&(r=I(r,fe(i,n,n.out)))),"directed"!==e&&(r=I(r,fe(i,n,n.undirected))),r}("mixed"===r?this.type:r,i,t)}}function ye(e,t){var n={key:e};return Object.keys(t.attributes).length&&(n.attributes=d({},t.attributes)),n}function ve(e,t){var n={source:t.source.key,target:t.target.key};return t.generatedKey||(n.key=e),Object.keys(t.attributes).length&&(n.attributes=d({},t.attributes)),t instanceof T&&(n.undirected=!0),n}function we(e){return h(e)?"key"in e?!("attributes"in e)||h(e.attributes)&&null!==e.attributes?null:"invalid-attributes":"no-key":"not-object"}function be(e){return h(e)?"source"in e?"target"in e?!("attributes"in e)||h(e.attributes)&&null!==e.attributes?"undirected"in e&&"boolean"!=typeof e.undirected?"invalid-undirected":null:"invalid-attributes":"no-target":"no-source":"not-object"}var me=new Set(["directed","undirected","mixed"]),_e=new Set(["domain","_events","_eventsCount","_maxListeners"]),Ge={allowSelfLoops:!0,edgeKeyGenerator:null,multi:!1,type:"mixed"};function Ee(e,t,n,r,i,o,a,c){if(!r&&"undirected"===e.type)throw new z("Graph.".concat(t,": you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead."));if(r&&"directed"===e.type)throw new z("Graph.".concat(t,": you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead."));if(c&&!h(c))throw new j("Graph.".concat(t,': invalid attributes. Expecting an object but got "').concat(c,'"'));if(o=""+o,a=""+a,c=c||{},!e.allowSelfLoops&&o===a)throw new z("Graph.".concat(t,': source & target are the same ("').concat(o,"\"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false."));var d=e._nodes.get(o),u=e._nodes.get(a);if(!d)throw new U("Graph.".concat(t,': source node "').concat(o,'" not found.'));if(!u)throw new U("Graph.".concat(t,': target node "').concat(a,'" not found.'));var s={key:null,undirected:r,source:o,target:a,attributes:c};if(n&&(i=e._edgeKeyGenerator(s)),i=""+i,e._edges.has(i))throw new z("Graph.".concat(t,': the "').concat(i,'" edge already exists in the graph.'));if(!e.multi&&(r?void 0!==d.undirected[a]:void 0!==d.out[a]))throw new z("Graph.".concat(t,': an edge linking "').concat(o,'" to "').concat(a,"\" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option."));var f=new(r?T:C)(i,n,d,u,c);return e._edges.set(i,f),o===a?r?d.undirectedSelfLoops++:d.directedSelfLoops++:r?(d.undirectedDegree++,u.undirectedDegree++):(d.outDegree++,u.inDegree++),P(e,r,f,o,a,d,u),r?e._undirectedSize++:e._directedSize++,s.key=i,e.emit("edgeAdded",s),i}function ke(e,t,n,r,i,o,a,c){if(!r&&"undirected"===e.type)throw new z("Graph.".concat(t,": you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead."));if(r&&"directed"===e.type)throw new z("Graph.".concat(t,": you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead."));if(c&&!h(c))throw new j("Graph.".concat(t,': invalid attributes. Expecting an object but got "').concat(c,'"'));if(o=""+o,a=""+a,c=c||{},!e.allowSelfLoops&&o===a)throw new z("Graph.".concat(t,': source & target are the same ("').concat(o,"\"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false."));var s,f,p=e._nodes.get(o),g=e._nodes.get(a),l=null;if(!n&&(s=e._edges.get(i))){if(s.source!==o||s.target!==a||r&&(s.source!==a||s.target!==o))throw new z("Graph.".concat(t,': inconsistency detected when attempting to merge the "').concat(i,'" edge with "').concat(o,'" source & "').concat(a,'" target vs. (').concat(s.source,", ").concat(s.target,")."));l=i}if(l||e.multi||!p||(r?void 0===p.undirected[a]:void 0===p.out[a])||(f=u(e,o,a,r?"undirected":"directed")),f)return c?(d(f.attributes,c),l):l;var y={key:null,undirected:r,source:o,target:a,attributes:c};if(n&&(i=e._edgeKeyGenerator(y)),i=""+i,e._edges.has(i))throw new z("Graph.".concat(t,': the "').concat(i,'" edge already exists in the graph.'));return p||(e.addNode(o),p=e._nodes.get(o),o===a&&(g=p)),g||(e.addNode(a),g=e._nodes.get(a)),s=new(r?T:C)(i,n,p,g,c),e._edges.set(i,s),o===a?r?p.undirectedSelfLoops++:p.directedSelfLoops++:r?(p.undirectedDegree++,g.undirectedDegree++):(p.outDegree++,g.inDegree++),P(e,r,s,o,a,p,g),r?e._undirectedSize++:e._directedSize++,y.key=i,e.emit("edgeAdded",y),i}var xe=function(e){function n(t){var n;if(n=e.call(this)||this,(t=d({},Ge,t)).edgeKeyGenerator&&"function"!=typeof t.edgeKeyGenerator)throw new j("Graph.constructor: invalid 'edgeKeyGenerator' option. Expecting a function but got \"".concat(t.edgeKeyGenerator,'".'));if("boolean"!=typeof t.multi)throw new j("Graph.constructor: invalid 'multi' option. Expecting a boolean but got \"".concat(t.multi,'".'));if(!me.has(t.type))throw new j('Graph.constructor: invalid \'type\' option. Should be one of "mixed", "directed" or "undirected" but got "'.concat(t.type,'".'));if("boolean"!=typeof t.allowSelfLoops)throw new j("Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got \"".concat(t.allowSelfLoops,'".'));var r,i="mixed"===t.type?O:"directed"===t.type?K:M;return p(c(n),"NodeDataClass",i),p(c(n),"_attributes",{}),p(c(n),"_nodes",new Map),p(c(n),"_edges",new Map),p(c(n),"_directedSize",0),p(c(n),"_undirectedSize",0),p(c(n),"_edgeKeyGenerator",t.edgeKeyGenerator||(r=0,function(){return"_geid".concat(r++,"_")})),p(c(n),"_options",t),_e.forEach((function(e){return p(c(n),e,n[e])})),g(c(n),"order",(function(){return n._nodes.size})),g(c(n),"size",(function(){return n._edges.size})),g(c(n),"directedSize",(function(){return n._directedSize})),g(c(n),"undirectedSize",(function(){return n._undirectedSize})),g(c(n),"multi",n._options.multi),g(c(n),"type",n._options.type),g(c(n),"allowSelfLoops",n._options.allowSelfLoops),n}t(n,e);var r=n.prototype;return r.hasNode=function(e){return this._nodes.has(""+e)},r.hasDirectedEdge=function(e,t){if("undirected"===this.type)return!1;if(1===arguments.length){var n=""+e,r=this._edges.get(n);return!!r&&r instanceof C}if(2===arguments.length){e=""+e,t=""+t;var i=this._nodes.get(e);if(!i)return!1;var o=i.out[t];return!!o&&(!this.multi||!!o.size)}throw new j("Graph.hasDirectedEdge: invalid arity (".concat(arguments.length,", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target."))},r.hasUndirectedEdge=function(e,t){if("directed"===this.type)return!1;if(1===arguments.length){var n=""+e,r=this._edges.get(n);return!!r&&r instanceof T}if(2===arguments.length){e=""+e,t=""+t;var i=this._nodes.get(e);if(!i)return!1;var o=i.undirected[t];return!!o&&(!this.multi||!!o.size)}throw new j("Graph.hasDirectedEdge: invalid arity (".concat(arguments.length,", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target."))},r.hasEdge=function(e,t){if(1===arguments.length){var n=""+e;return this._edges.has(n)}if(2===arguments.length){e=""+e,t=""+t;var r=this._nodes.get(e);if(!r)return!1;var i=void 0!==r.out&&r.out[t];return i||(i=void 0!==r.undirected&&r.undirected[t]),!!i&&(!this.multi||!!i.size)}throw new j("Graph.hasEdge: invalid arity (".concat(arguments.length,", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target."))},r.directedEdge=function(e,t){if("undirected"!==this.type){if(e=""+e,t=""+t,this.multi)throw new z("Graph.directedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.directedEdges instead.");var n=this._nodes.get(e);if(!n)throw new U('Graph.directedEdge: could not find the "'.concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new U('Graph.directedEdge: could not find the "'.concat(t,'" target node in the graph.'));var r=n.out&&n.out[t]||void 0;return r?r.key:void 0}},r.undirectedEdge=function(e,t){if("directed"!==this.type){if(e=""+e,t=""+t,this.multi)throw new z("Graph.undirectedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.undirectedEdges instead.");var n=this._nodes.get(e);if(!n)throw new U('Graph.undirectedEdge: could not find the "'.concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new U('Graph.undirectedEdge: could not find the "'.concat(t,'" target node in the graph.'));var r=n.undirected&&n.undirected[t]||void 0;return r?r.key:void 0}},r.edge=function(e,t){if(this.multi)throw new z("Graph.edge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.edges instead.");e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new U('Graph.edge: could not find the "'.concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new U('Graph.edge: could not find the "'.concat(t,'" target node in the graph.'));var r=n.out&&n.out[t]||n.undirected&&n.undirected[t]||void 0;if(r)return r.key},r.inDegree=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("boolean"!=typeof t)throw new j('Graph.inDegree: Expecting a boolean but got "'.concat(t,'" for the second parameter (allowing self-loops to be counted).'));e=""+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.inDegree: could not find the "'.concat(e,'" node in the graph.'));if("undirected"===this.type)return 0;var r=t?n.directedSelfLoops:0;return n.inDegree+r},r.outDegree=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("boolean"!=typeof t)throw new j('Graph.outDegree: Expecting a boolean but got "'.concat(t,'" for the second parameter (allowing self-loops to be counted).'));e=""+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.outDegree: could not find the "'.concat(e,'" node in the graph.'));if("undirected"===this.type)return 0;var r=t?n.directedSelfLoops:0;return n.outDegree+r},r.directedDegree=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("boolean"!=typeof t)throw new j('Graph.directedDegree: Expecting a boolean but got "'.concat(t,'" for the second parameter (allowing self-loops to be counted).'));if(e=""+e,!this.hasNode(e))throw new U('Graph.directedDegree: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:this.inDegree(e,t)+this.outDegree(e,t)},r.undirectedDegree=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("boolean"!=typeof t)throw new j('Graph.undirectedDegree: Expecting a boolean but got "'.concat(t,'" for the second parameter (allowing self-loops to be counted).'));if(e=""+e,!this.hasNode(e))throw new U('Graph.undirectedDegree: could not find the "'.concat(e,'" node in the graph.'));if("directed"===this.type)return 0;var n=this._nodes.get(e),r=t?2*n.undirectedSelfLoops:0;return n.undirectedDegree+r},r.degree=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("boolean"!=typeof t)throw new j('Graph.degree: Expecting a boolean but got "'.concat(t,'" for the second parameter (allowing self-loops to be counted).'));if(e=""+e,!this.hasNode(e))throw new U('Graph.degree: could not find the "'.concat(e,'" node in the graph.'));var n=0;return"undirected"!==this.type&&(n+=this.directedDegree(e,t)),"directed"!==this.type&&(n+=this.undirectedDegree(e,t)),n},r.source=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new U('Graph.source: could not find the "'.concat(e,'" edge in the graph.'));return t.source.key},r.target=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new U('Graph.target: could not find the "'.concat(e,'" edge in the graph.'));return t.target.key},r.extremities=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new U('Graph.extremities: could not find the "'.concat(e,'" edge in the graph.'));return[t.source.key,t.target.key]},r.opposite=function(e,t){if(e=""+e,t=""+t,!this._nodes.has(e))throw new U('Graph.opposite: could not find the "'.concat(e,'" node in the graph.'));var n=this._edges.get(t);if(!n)throw new U('Graph.opposite: could not find the "'.concat(t,'" edge in the graph.'));var r=n.source,i=n.target,o=r.key,a=i.key;if(e!==o&&e!==a)throw new U('Graph.opposite: the "'.concat(e,'" node is not attached to the "').concat(t,'" edge (').concat(o,", ").concat(a,")."));return e===o?a:o},r.undirected=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new U('Graph.undirected: could not find the "'.concat(e,'" edge in the graph.'));return t instanceof T},r.directed=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new U('Graph.directed: could not find the "'.concat(e,'" edge in the graph.'));return t instanceof C},r.selfLoop=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new U('Graph.selfLoop: could not find the "'.concat(e,'" edge in the graph.'));return t.source===t.target},r.addNode=function(e,t){if(t&&!h(t))throw new j('Graph.addNode: invalid attributes. Expecting an object but got "'.concat(t,'"'));if(e=""+e,t=t||{},this._nodes.has(e))throw new z('Graph.addNode: the "'.concat(e,'" node already exist in the graph.'));var n=new this.NodeDataClass(e,t);return this._nodes.set(e,n),this.emit("nodeAdded",{key:e,attributes:t}),e},r.mergeNode=function(e,t){if(t&&!h(t))throw new j('Graph.mergeNode: invalid attributes. Expecting an object but got "'.concat(t,'"'));e=""+e,t=t||{};var n=this._nodes.get(e);return n?(t&&d(n.attributes,t),e):(n=new this.NodeDataClass(e,t),this._nodes.set(e,n),this.emit("nodeAdded",{key:e,attributes:t}),e)},r.dropNode=function(e){if(e=""+e,!this.hasNode(e))throw new U('Graph.dropNode: could not find the "'.concat(e,'" node in the graph.'));for(var t=this.edges(e),n=0,r=t.length;n1){var n=""+arguments[0],r=""+arguments[1];if(!(t=u(this,n,r,this.type)))throw new U('Graph.dropEdge: could not find the "'.concat(n,'" -> "').concat(r,'" edge in the graph.'))}else if(e=""+e,!(t=this._edges.get(e)))throw new U('Graph.dropEdge: could not find the "'.concat(e,'" edge in the graph.'));this._edges.delete(t.key);var i=t,o=i.source,a=i.target,c=i.attributes,d=t instanceof T;return o===a?o.selfLoops--:d?(o.undirectedDegree--,a.undirectedDegree--):(o.outDegree--,a.inDegree--),W(this,d,t),d?this._undirectedSize--:this._directedSize--,this.emit("edgeDropped",{key:e,attributes:c,source:o.key,target:a.key,undirected:d}),this},r.clear=function(){this._edges.clear(),this._nodes.clear(),this.emit("cleared")},r.clearEdges=function(){this._edges.clear(),this.clearIndex(),this.emit("edgesCleared")},r.getAttribute=function(e){return this._attributes[e]},r.getAttributes=function(){return this._attributes},r.hasAttribute=function(e){return this._attributes.hasOwnProperty(e)},r.setAttribute=function(e,t){return this._attributes[e]=t,this.emit("attributesUpdated",{type:"set",meta:{name:e,value:t}}),this},r.updateAttribute=function(e,t){if("function"!=typeof t)throw new j("Graph.updateAttribute: updater should be a function.");return this._attributes[e]=t(this._attributes[e]),this.emit("attributesUpdated",{type:"set",meta:{name:e,value:this._attributes[e]}}),this},r.removeAttribute=function(e){return delete this._attributes[e],this.emit("attributesUpdated",{type:"remove",meta:{name:e}}),this},r.replaceAttributes=function(e){if(!h(e))throw new j("Graph.replaceAttributes: provided attributes are not a plain object.");var t=this._attributes;return this._attributes=e,this.emit("attributesUpdated",{type:"replace",meta:{before:t,after:e}}),this},r.mergeAttributes=function(e){if(!h(e))throw new j("Graph.mergeAttributes: provided attributes are not a plain object.");return this._attributes=d(this._attributes,e),this.emit("attributesUpdated",{type:"merge",meta:{data:this._attributes}}),this},r.getNodeAttribute=function(e,t){e=""+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.getNodeAttribute: could not find the "'.concat(e,'" node in the graph.'));return n.attributes[t]},r.getNodeAttributes=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new U('Graph.getNodeAttributes: could not find the "'.concat(e,'" node in the graph.'));return t.attributes},r.hasNodeAttribute=function(e,t){e=""+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.hasNodeAttribute: could not find the "'.concat(e,'" node in the graph.'));return n.attributes.hasOwnProperty(t)},r.setNodeAttribute=function(e,t,n){e=""+e;var r=this._nodes.get(e);if(!r)throw new U('Graph.setNodeAttribute: could not find the "'.concat(e,'" node in the graph.'));if(arguments.length<3)throw new j("Graph.setNodeAttribute: not enough arguments. Either you forgot to pass the attribute's name or value, or you meant to use #.replaceNodeAttributes / #.mergeNodeAttributes instead.");return r.attributes[t]=n,this.emit("nodeAttributesUpdated",{key:e,type:"set",meta:{name:t,value:n}}),this},r.updateNodeAttribute=function(e,t,n){e=""+e;var r=this._nodes.get(e);if(!r)throw new U('Graph.updateNodeAttribute: could not find the "'.concat(e,'" node in the graph.'));if(arguments.length<3)throw new j("Graph.updateNodeAttribute: not enough arguments. Either you forgot to pass the attribute's name or updater, or you meant to use #.replaceNodeAttributes / #.mergeNodeAttributes instead.");if("function"!=typeof n)throw new j("Graph.updateAttribute: updater should be a function.");var i=r.attributes;return i[t]=n(i[t]),this.emit("nodeAttributesUpdated",{key:e,type:"set",meta:{name:t,value:i[t]}}),this},r.removeNodeAttribute=function(e,t){e=""+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.hasNodeAttribute: could not find the "'.concat(e,'" node in the graph.'));return delete n.attributes[t],this.emit("nodeAttributesUpdated",{key:e,type:"remove",meta:{name:t}}),this},r.replaceNodeAttributes=function(e,t){e=""+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.replaceNodeAttributes: could not find the "'.concat(e,'" node in the graph.'));if(!h(t))throw new j("Graph.replaceNodeAttributes: provided attributes are not a plain object.");var r=n.attributes;return n.attributes=t,this.emit("nodeAttributesUpdated",{key:e,type:"replace",meta:{before:r,after:t}}),this},r.mergeNodeAttributes=function(e,t){e=""+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.mergeNodeAttributes: could not find the "'.concat(e,'" node in the graph.'));if(!h(t))throw new j("Graph.mergeNodeAttributes: provided attributes are not a plain object.");return d(n.attributes,t),this.emit("nodeAttributesUpdated",{key:e,type:"merge",meta:{data:t}}),this},r.forEach=function(e){if("function"!=typeof e)throw new j("Graph.forEach: expecting a callback.");this._edges.forEach((function(t,n){var r=t.source,i=t.target;e(r.key,i.key,r.attributes,i.attributes,n,t.attributes)}))},r.adjacency=function(){var e=this._edges.values();return new N((function(){var t=e.next();if(t.done)return t;var n=t.value,r=n.source,i=n.target;return{done:!1,value:[r.key,i.key,r.attributes,i.attributes,n.key,n.attributes]}}))},r.nodes=function(){return D(this._nodes.keys(),this._nodes.size)},r.forEachNode=function(e){if("function"!=typeof e)throw new j("Graph.forEachNode: expecting a callback.");this._nodes.forEach((function(t,n){e(n,t.attributes)}))},r.nodeEntries=function(){var e=this._nodes.values();return new N((function(){var t=e.next();if(t.done)return t;var n=t.value;return{value:[n.key,n.attributes],done:!1}}))},r.exportNode=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new U('Graph.exportNode: could not find the "'.concat(e,'" node in the graph.'));return ye(e,t)},r.exportEdge=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new U('Graph.exportEdge: could not find the "'.concat(e,'" edge in the graph.'));return ve(e,t)},r.export=function(){var e=new Array(this._nodes.size),t=0;this._nodes.forEach((function(n,r){e[t++]=ye(r,n)}));var n=new Array(this._edges.size);return t=0,this._edges.forEach((function(e,r){n[t++]=ve(r,e)})),{attributes:this.getAttributes(),nodes:e,edges:n}},r.importNode=function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=we(e);if(n){if("not-object"===n)throw new j('Graph.importNode: invalid serialized node. A serialized node should be a plain object with at least a "key" property.');if("no-key"===n)throw new j("Graph.importNode: no key provided.");if("invalid-attributes"===n)throw new j("Graph.importNode: invalid attributes. Attributes should be a plain object, null or omitted.")}var r=e.key,i=e.attributes,o=void 0===i?{}:i;return t?this.mergeNode(r,o):this.addNode(r,o),this},r.importEdge=function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=be(e);if(n){if("not-object"===n)throw new j('Graph.importEdge: invalid serialized edge. A serialized edge should be a plain object with at least a "source" & "target" property.');if("no-source"===n)throw new j("Graph.importEdge: missing souce.");if("no-target"===n)throw new j("Graph.importEdge: missing target.");if("invalid-attributes"===n)throw new j("Graph.importEdge: invalid attributes. Attributes should be a plain object, null or omitted.");if("invalid-undirected"===n)throw new j("Graph.importEdge: invalid undirected. Undirected should be boolean or omitted.")}var r=e.source,i=e.target,o=e.attributes,a=void 0===o?{}:o,c=e.undirected,d=void 0!==c&&c;return"key"in e?(t?d?this.mergeUndirectedEdgeWithKey:this.mergeDirectedEdgeWithKey:d?this.addUndirectedEdgeWithKey:this.addDirectedEdgeWithKey).call(this,e.key,r,i,a):(t?d?this.mergeUndirectedEdge:this.mergeDirectedEdge:d?this.addUndirectedEdge:this.addDirectedEdge).call(this,r,i,a),this},r.import=function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(s(e))return this.import(e.export(),n),this;if(!h(e))throw new j("Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.");if(e.attributes){if(!h(e.attributes))throw new j("Graph.import: invalid attributes. Expecting a plain object.");n?this.mergeAttributes(e.attributes):this.replaceAttributes(e.attributes)}return e.nodes&&e.nodes.forEach((function(e){return t.importNode(e,n)})),e.edges&&e.edges.forEach((function(e){return t.importEdge(e,n)})),this},r.nullCopy=function(e){return new n(d({},this._options,e))},r.emptyCopy=function(e){var t=new n(d({},this._options,e));return this._nodes.forEach((function(e,n){e=new t.NodeDataClass(n,d({},e.attributes)),t._nodes.set(n,e)})),t},r.copy=function(){var e=new n(this._options);return e.import(this),e},r.upgradeToMixed=function(){return"mixed"===this.type||(this._nodes.forEach((function(e){return e.upgradeToMixed()})),this._options.type="mixed",g(this,"type",this._options.type),p(this,"NodeDataClass",O)),this},r.upgradeToMulti=function(){return this.multi||(this._options.multi=!0,g(this,"multi",!0),(e=this)._nodes.forEach((function(t,n){if(t.out)for(var r in t.out){var i=new Set;i.add(t.out[r]),t.out[r]=i,e._nodes.get(r).in[n]=i}if(t.undirected)for(var o in t.undirected)if(!(o>n)){var a=new Set;a.add(t.undirected[o]),t.undirected[o]=a,e._nodes.get(o).undirected[n]=a}}))),this;var e},r.clearIndex=function(){return this._nodes.forEach((function(e){void 0!==e.in&&(e.in={},e.out={}),void 0!==e.undirected&&(e.undirected={})})),this},r.toJSON=function(){return this.export()},r.toString=function(){var e=this.order>1||0===this.order,t=this.size>1||0===this.size;return"Graph<".concat(f(this.order)," node").concat(e?"s":"",", ").concat(f(this.size)," edge").concat(t?"s":"",">")},r.inspect=function(){var e=this,t={};this._nodes.forEach((function(e,n){t[n]=e.attributes}));var n={},r={};this._edges.forEach((function(t,i){var o=t instanceof T?"--":"->",a="",c="(".concat(t.source.key,")").concat(o,"(").concat(t.target.key,")");t.generatedKey?e.multi&&(void 0===r[c]?r[c]=0:r[c]++,a+="".concat(r[c],". ")):a+="[".concat(i,"]: "),n[a+=c]=t.attributes}));var i={};for(var o in this)this.hasOwnProperty(o)&&!_e.has(o)&&"function"!=typeof this[o]&&(i[o]=this[o]);return i.attributes=this._attributes,i.nodes=t,i.edges=n,p(i,"constructor",this.constructor),i},n}(y);"undefined"!=typeof Symbol&&(xe.prototype[Symbol.for("nodejs.util.inspect.custom")]=xe.prototype.inspect),[{name:function(e){return"".concat(e,"Edge")},generateKey:!0},{name:function(e){return"".concat(e,"DirectedEdge")},generateKey:!0,type:"directed"},{name:function(e){return"".concat(e,"UndirectedEdge")},generateKey:!0,type:"undirected"},{name:function(e){return"".concat(e,"EdgeWithKey")}},{name:function(e){return"".concat(e,"DirectedEdgeWithKey")},type:"directed"},{name:function(e){return"".concat(e,"UndirectedEdgeWithKey")},type:"undirected"}].forEach((function(e){["add","merge"].forEach((function(t){var n=e.name(t),r="add"===t?Ee:ke;e.generateKey?xe.prototype[n]=function(t,i,o){return r(this,n,!0,"undirected"===(e.type||this.type),null,t,i,o)}:xe.prototype[n]=function(t,i,o,a){return r(this,n,!1,"undirected"===(e.type||this.type),t,i,o,a)}}))})),"undefined"!=typeof Symbol&&(xe.prototype[Symbol.iterator]=xe.prototype.adjacency),function(e){R.forEach((function(t){var n=t.name,r=t.attacher;r(e,n("Edge"),"mixed",C),r(e,n("DirectedEdge"),"directed",C),r(e,n("UndirectedEdge"),"undirected",T)}))}(xe),function(e){F.forEach((function(t){!function(e,t){var n=t.name,r=t.type,i=t.direction;e.prototype[n]=function(e,t){if("mixed"!==r&&"mixed"!==this.type&&r!==this.type)return[];if(!arguments.length)return X(this,r);if(1===arguments.length){e=""+e;var o=this._nodes.get(e);if(void 0===o)throw new U("Graph.".concat(n,': could not find the "').concat(e,'" node in the graph.'));return ee("mixed"===r?this.type:r,i,o)}if(2===arguments.length){e=""+e,t=""+t;var a=this._nodes.get(e);if(!a)throw new U("Graph.".concat(n,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new U("Graph.".concat(n,': could not find the "').concat(t,'" target node in the graph.'));return re(r,i,a,t)}throw new j("Graph.".concat(n,": too many arguments (expecting 0, 1 or 2 and got ").concat(arguments.length,")."))}}(e,t),function(e,t){var n=t.name,r=t.type,i=t.direction,o="forEach"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(e,t,n){if("mixed"===r||"mixed"===this.type||r===this.type){if(1===arguments.length)return Z(this,r,n=e);if(2===arguments.length){e=""+e,n=t;var a=this._nodes.get(e);if(void 0===a)throw new U("Graph.".concat(o,': could not find the "').concat(e,'" node in the graph.'));return te(this.multi,"mixed"===r?this.type:r,i,a,n)}if(3===arguments.length){e=""+e,t=""+t;var c=this._nodes.get(e);if(!c)throw new U("Graph.".concat(o,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new U("Graph.".concat(o,': could not find the "').concat(t,'" target node in the graph.'));return ie(r,i,c,t,n)}throw new j("Graph.".concat(o,": too many arguments (expecting 1, 2 or 3 and got ").concat(arguments.length,")."))}}}(e,t),function(e,t){var n=t.name,r=t.type,i=t.direction,o=n.slice(0,-1)+"Entries";e.prototype[o]=function(e,t){if("mixed"!==r&&"mixed"!==this.type&&r!==this.type)return N.empty();if(!arguments.length)return $(this,r);if(1===arguments.length){e=""+e;var n=this._nodes.get(e);if(!n)throw new U("Graph.".concat(o,': could not find the "').concat(e,'" node in the graph.'));return ne(r,i,n)}if(2===arguments.length){e=""+e,t=""+t;var a=this._nodes.get(e);if(!a)throw new U("Graph.".concat(o,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new U("Graph.".concat(o,': could not find the "').concat(t,'" target node in the graph.'));return oe(r,i,a,t)}throw new j("Graph.".concat(o,": too many arguments (expecting 0, 1 or 2 and got ").concat(arguments.length,")."))}}(e,t)}))}(xe),function(e){ae.forEach((function(t){!function(e,t){var n=t.name,r=t.type,i=t.direction;e.prototype[n]=function(e){if("mixed"!==r&&"mixed"!==this.type&&r!==this.type)return[];if(2===arguments.length){var t=""+arguments[0],o=""+arguments[1];if(!this._nodes.has(t))throw new U("Graph.".concat(n,': could not find the "').concat(t,'" node in the graph.'));if(!this._nodes.has(o))throw new U("Graph.".concat(n,': could not find the "').concat(o,'" node in the graph.'));return pe(this,r,i,t,o)}if(1===arguments.length){e=""+e;var a=this._nodes.get(e);if(void 0===a)throw new U("Graph.".concat(n,': could not find the "').concat(e,'" node in the graph.'));var c=de("mixed"===r?this.type:r,i,a);return c}throw new j("Graph.".concat(n,": invalid number of arguments (expecting 1 or 2 and got ").concat(arguments.length,")."))}}(e,t),ge(e,t),le(e,t)}))}(xe);var Se=function(e){function n(t){return e.call(this,d({type:"directed"},t))||this}return t(n,e),n}(xe),Ae=function(e){function n(t){return e.call(this,d({type:"undirected"},t))||this}return t(n,e),n}(xe),Ne=function(e){function n(t){return e.call(this,d({multi:!0},t))||this}return t(n,e),n}(xe),De=function(e){function n(t){return e.call(this,d({multi:!0,type:"directed"},t))||this}return t(n,e),n}(xe),Le=function(e){function n(t){return e.call(this,d({multi:!0,type:"undirected"},t))||this}return t(n,e),n}(xe);function je(e){e.from=function(t,n){var r=new e(n);return r.import(t),r}}return je(xe),je(Se),je(Ae),je(Ne),je(De),je(Le),xe.Graph=xe,xe.DirectedGraph=Se,xe.UndirectedGraph=Ae,xe.MultiGraph=Ne,xe.MultiDirectedGraph=De,xe.MultiUndirectedGraph=Le,xe.InvalidArgumentsGraphError=j,xe.NotFoundGraphError=U,xe.UsageGraphError=z,xe})); },{}],112:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],113:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } },{}],114:[function(require,module,exports){ "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } exports.__esModule = true; __export(require("./isMobile")); var isMobile_1 = require("./isMobile"); exports["default"] = isMobile_1["default"]; },{"./isMobile":115}],115:[function(require,module,exports){ "use strict"; exports.__esModule = true; var appleIphone = /iPhone/i; var appleIpod = /iPod/i; var appleTablet = /iPad/i; var appleUniversal = /\biOS-universal(?:.+)Mac\b/i; var androidPhone = /\bAndroid(?:.+)Mobile\b/i; var androidTablet = /Android/i; var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i; var amazonTablet = /Silk/i; var windowsPhone = /Windows Phone/i; var windowsTablet = /\bWindows(?:.+)ARM\b/i; var otherBlackBerry = /BlackBerry/i; var otherBlackBerry10 = /BB10/i; var otherOpera = /Opera Mini/i; var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i; var otherFirefox = /Mobile(?:.+)Firefox\b/i; var isAppleTabletOnIos13 = function (navigator) { return (typeof navigator !== 'undefined' && navigator.platform === 'MacIntel' && typeof navigator.maxTouchPoints === 'number' && navigator.maxTouchPoints > 1 && typeof MSStream === 'undefined'); }; function createMatch(userAgent) { return function (regex) { return regex.test(userAgent); }; } function isMobile(param) { var nav = { userAgent: '', platform: '', maxTouchPoints: 0 }; if (!param && typeof navigator !== 'undefined') { nav = { userAgent: navigator.userAgent, platform: navigator.platform, maxTouchPoints: navigator.maxTouchPoints || 0 }; } else if (typeof param === 'string') { nav.userAgent = param; } else if (param && param.userAgent) { nav = { userAgent: param.userAgent, platform: param.platform, maxTouchPoints: param.maxTouchPoints || 0 }; } var userAgent = nav.userAgent; var tmp = userAgent.split('[FBAN'); if (typeof tmp[1] !== 'undefined') { userAgent = tmp[0]; } tmp = userAgent.split('Twitter'); if (typeof tmp[1] !== 'undefined') { userAgent = tmp[0]; } var match = createMatch(userAgent); var result = { apple: { phone: match(appleIphone) && !match(windowsPhone), ipod: match(appleIpod), tablet: !match(appleIphone) && (match(appleTablet) || isAppleTabletOnIos13(nav)) && !match(windowsPhone), universal: match(appleUniversal), device: (match(appleIphone) || match(appleIpod) || match(appleTablet) || match(appleUniversal) || isAppleTabletOnIos13(nav)) && !match(windowsPhone) }, amazon: { phone: match(amazonPhone), tablet: !match(amazonPhone) && match(amazonTablet), device: match(amazonPhone) || match(amazonTablet) }, android: { phone: (!match(windowsPhone) && match(amazonPhone)) || (!match(windowsPhone) && match(androidPhone)), tablet: !match(windowsPhone) && !match(amazonPhone) && !match(androidPhone) && (match(amazonTablet) || match(androidTablet)), device: (!match(windowsPhone) && (match(amazonPhone) || match(amazonTablet) || match(androidPhone) || match(androidTablet))) || match(/\bokhttp\b/i) }, windows: { phone: match(windowsPhone), tablet: match(windowsTablet), device: match(windowsPhone) || match(windowsTablet) }, other: { blackberry: match(otherBlackBerry), blackberry10: match(otherBlackBerry10), opera: match(otherOpera), firefox: match(otherFirefox), chrome: match(otherChrome), device: match(otherBlackBerry) || match(otherBlackBerry10) || match(otherOpera) || match(otherFirefox) || match(otherChrome) }, any: false, phone: false, tablet: false }; result.any = result.apple.device || result.android.device || result.windows.device || result.other.device; result.phone = result.apple.phone || result.android.phone || result.windows.phone; result.tablet = result.apple.tablet || result.android.tablet || result.windows.tablet; return result; } exports["default"] = isMobile; },{}],116:[function(require,module,exports){ /*! * jQuery JavaScript Library v3.5.1 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2020-05-04T22:49Z */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var getProto = Object.getPrototypeOf; var slice = arr.slice; var flat = arr.flat ? function( array ) { return arr.flat.call( array ); } : function( array ) { return arr.concat.apply( [], array ); }; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; var isFunction = function isFunction( obj ) { // Support: Chrome <=57, Firefox <=52 // In some browsers, typeof returns "function" for HTML elements // (i.e., `typeof document.createElement( "object" ) === "function"`). // We don't want to classify *any* DOM node as a function. return typeof obj === "function" && typeof obj.nodeType !== "number"; }; var isWindow = function isWindow( obj ) { return obj != null && obj === obj.window; }; var document = window.document; var preservedScriptAttributes = { type: true, src: true, nonce: true, noModule: true }; function DOMEval( code, node, doc ) { doc = doc || document; var i, val, script = doc.createElement( "script" ); script.text = code; if ( node ) { for ( i in preservedScriptAttributes ) { // Support: Firefox 64+, Edge 18+ // Some browsers don't support the "nonce" property on scripts. // On the other hand, just using `getAttribute` is not enough as // the `nonce` attribute is reset to an empty string whenever it // becomes browsing-context connected. // See https://github.com/whatwg/html/issues/2369 // See https://html.spec.whatwg.org/#nonce-attributes // The `node.getAttribute` check was added for the sake of // `jQuery.globalEval` so that it can fake a nonce-containing node // via an object. val = node[ i ] || node.getAttribute && node.getAttribute( i ); if ( val ) { script.setAttribute( i, val ); } } } doc.head.appendChild( script ).parentNode.removeChild( script ); } function toType( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; } /* global Symbol */ // Defining this global in .eslintrc.json would create a danger of using the global // unguarded in another place, it seems safer to define global only for this module var version = "3.5.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { // Return all the elements in a clean array if ( num == null ) { return slice.call( this ); } // Return just the one element from the set return num < 0 ? this[ num + this.length ] : this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, even: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return ( i + 1 ) % 2; } ) ); }, odd: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return i % 2; } ) ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { copy = options[ name ]; // Prevent Object.prototype pollution // Prevent never-ending loop if ( name === "__proto__" || target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = Array.isArray( copy ) ) ) ) { src = target[ name ]; // Ensure proper type for the source value if ( copyIsArray && !Array.isArray( src ) ) { clone = []; } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { clone = {}; } else { clone = src; } copyIsArray = false; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, // Evaluates a script in a provided context; falls back to the global one // if not specified. globalEval: function( code, options, doc ) { DOMEval( code, { nonce: options && options.nonce }, doc ); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return flat( ret ); }, // A global GUID counter for objects guid: 1, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( _i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = toType( obj ); if ( isFunction( obj ) || isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.3.5 * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * * Date: 2020-03-14 */ ( function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ( {} ).hasOwnProperty, arr = [], pop = arr.pop, pushNative = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[ i ] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + "ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] // or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), funescape = function( escape, nonHex ) { var high = "0x" + escape.slice( 1 ) - 0x10000; return nonHex ? // Strip the backslash prefix from a non-hex escape sequence nonHex : // Replace a hexadecimal escape sequence with the encoded Unicode code point // Support: IE <=11+ // For values outside the Basic Multilingual Plane (BMP), manually construct a // surrogate pair high < 0 ? String.fromCharCode( high + 0x10000 ) : String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( ( arr = slice.call( preferredDoc.childNodes ) ), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply // eslint-disable-next-line no-unused-expressions arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { pushNative.apply( target, slice.call( els ) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( ( target[ j++ ] = els[ i++ ] ) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { setDocument( context ); context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { // ID selector if ( ( m = match[ 1 ] ) ) { // Document context if ( nodeType === 9 ) { if ( ( elem = context.getElementById( m ) ) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && ( elem = newContext.getElementById( m ) ) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[ 2 ] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && // Support: IE 8 only // Exclude object elements ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // The technique has to be used as well when a leading combinator is used // as such selectors are not recognized by querySelectorAll. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; // We can use :scope instead of the ID hack if the browser // supports it & if we're not changing the context. if ( newContext !== context || !support.scope ) { // Capture the context ID, setting it first if necessary if ( ( nid = context.getAttribute( "id" ) ) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", ( nid = expando ) ); } } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + toSelector( groups[ i ] ); } newSelector = groups.join( "," ); } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return ( cache[ key + " " ] = value ); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement( "fieldset" ); try { return !!fn( el ); } catch ( e ) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split( "|" ), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[ i ] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( ( cur = cur.nextSibling ) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return ( name === "input" || name === "button" ) && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction( function( argument ) { argument = +argument; return markFunction( function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ ( j = matchIndexes[ i ] ) ] ) { seed[ j ] = !( matches[ j ] = seed[ j ] ); } } } ); } ); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { var namespace = elem.namespaceURI, docElem = ( elem.ownerDocument || elem ).documentElement; // Support: IE <=8 // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes // https://bugs.jquery.com/ticket/4833 return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9 - 11+, Edge 12 - 18+ // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( preferredDoc != document && ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, // Safari 4 - 5 only, Opera <=11.6 - 12.x only // IE/Edge & older browsers don't support the :scope pseudo-class. // Support: Safari 6.0 only // Safari 6.0 supports :scope but it's an alias of :root there. support.scope = assert( function( el ) { docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); return typeof el.querySelectorAll !== "undefined" && !el.querySelectorAll( ":scope fieldset div" ).length; } ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert( function( el ) { el.className = "i"; return !el.getAttribute( "className" ); } ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert( function( el ) { el.appendChild( document.createComment( "" ) ); return !el.getElementsByTagName( "*" ).length; } ); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert( function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; } ); // ID filter and find if ( support.getById ) { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute( "id" ) === attrId; }; }; Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode( "id" ); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( ( elem = elems[ i++ ] ) ) { node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find[ "TAG" ] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( ( elem = results[ i++ ] ) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert( function( el ) { var input; // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "" + ""; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll( "[selected]" ).length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push( "~=" ); } // Support: IE 11+, Edge 15 - 18+ // IE 11/Edge don't find elements on a `[name='']` query in some cases. // Adding a temporary attribute to the document before the selection works // around the issue. // Interestingly, IE 10 & older don't seem to have the issue. input = document.createElement( "input" ); input.setAttribute( "name", "" ); el.appendChild( input ); if ( !el.querySelectorAll( "[name='']" ).length ) { rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + "*(?:''|\"\")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll( ":checked" ).length ) { rbuggyQSA.push( ":checked" ); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push( ".#.+[+~]" ); } // Support: Firefox <=3.6 - 5 only // Old Firefox doesn't throw on a badly-escaped identifier. el.querySelectorAll( "\\\f" ); rbuggyQSA.push( "[\\r\\n\\f]" ); } ); assert( function( el ) { el.innerHTML = "" + ""; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement( "input" ); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll( "[name=d]" ).length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: Opera 10 - 11 only // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll( "*,:x" ); rbuggyQSA.push( ",.*:" ); } ); } if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector ) ) ) ) { assert( function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); } ); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 ) ); } : function( a, b ) { if ( b ) { while ( ( b = b.parentNode ) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { // Choose the first element that is related to our preferred document // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( a == document || a.ownerDocument == preferredDoc && contains( preferredDoc, a ) ) { return -1; } // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( b == document || b.ownerDocument == preferredDoc && contains( preferredDoc, b ) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. /* eslint-disable eqeqeq */ return a == document ? -1 : b == document ? 1 : /* eslint-enable eqeqeq */ aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( ( cur = cur.parentNode ) ) { ap.unshift( cur ); } cur = b; while ( ( cur = cur.parentNode ) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[ i ] === bp[ i ] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[ i ], bp[ i ] ) : // Otherwise nodes in our document sort first // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. /* eslint-disable eqeqeq */ ap[ i ] == preferredDoc ? -1 : bp[ i ] == preferredDoc ? 1 : /* eslint-enable eqeqeq */ 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { setDocument( elem ); if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch ( e ) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( ( context.ownerDocument || context ) != document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( ( elem.ownerDocument || elem ) != document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return ( sel + "" ).replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( ( elem = results[ i++ ] ) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( ( node = elem[ i++ ] ) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[ 1 ] = match[ 1 ].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ).replace( runescape, funescape ); if ( match[ 2 ] === "~=" ) { match[ 3 ] = " " + match[ 3 ] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[ 1 ] = match[ 1 ].toLowerCase(); if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[ 4 ] = +( match[ 4 ] ? match[ 5 ] + ( match[ 6 ] || 1 ) : 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); // other types prohibit arguments } else if ( match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[ 6 ] && match[ 2 ]; if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { return null; } // Accept quoted arguments as-is if ( match[ 3 ] ) { match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) ( excess = tokenize( unquoted, true ) ) && // advance to the next closing parenthesis ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { // excess is a negative index match[ 0 ] = match[ 0 ].slice( 0, excess ); match[ 2 ] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || ( pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute( "class" ) || "" ); } ); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; /* eslint-disable max-len */ return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; /* eslint-enable max-len */ }; }, "CHILD": function( type, what, _argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, _context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( ( node = node[ dir ] ) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( ( node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start ( diff = nodeIndex = 0 ) || start.pop() ) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( ( node = ++nodeIndex && node && node[ dir ] || ( diff = nodeIndex = 0 ) || start.pop() ) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction( function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[ i ] ); seed[ idx ] = !( matches[ idx ] = matched[ i ] ); } } ) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction( function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction( function( seed, matches, _context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( ( elem = unmatched[ i ] ) ) { seed[ i ] = !( matches[ i ] = elem ); } } } ) : function( elem, _context, xml ) { input[ 0 ] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[ 0 ] = null; return !results.pop(); }; } ), "has": markFunction( function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; } ), "contains": markFunction( function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; }; } ), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test( lang || "" ) ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( ( elemLang = documentIsHTML ? elem.lang : elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); return false; }; } ), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && ( !document.hasFocus || document.hasFocus() ) && !!( elem.type || elem.href || ~elem.tabIndex ); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return ( nodeName === "input" && !!elem.checked ) || ( nodeName === "option" && !!elem.selected ); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { // eslint-disable-next-line no-unused-expressions elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos[ "empty" ]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( ( attr = elem.getAttribute( "type" ) ) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo( function() { return [ 0 ]; } ), "last": createPositionalPseudo( function( _matchIndexes, length ) { return [ length - 1 ]; } ), "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; } ), "even": createPositionalPseudo( function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "odd": createPositionalPseudo( function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument > length ? length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; } ), "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; } ) } }; Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || ( match = rcomma.exec( soFar ) ) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[ 0 ].length ) || soFar; } groups.push( ( tokens = [] ) ); } matched = false; // Combinators if ( ( match = rcombinators.exec( soFar ) ) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[ 0 ].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || ( match = preFilters[ type ]( match ) ) ) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[ i ].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || ( elem[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || ( outerCache[ elem.uniqueID ] = {} ); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( ( oldCache = uniqueCache[ key ] ) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return ( newCache[ 2 ] = oldCache[ 2 ] ); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[ i ]( elem, context, xml ) ) { return false; } } return true; } : matchers[ 0 ]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[ i ], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( ( elem = unmatched[ i ] ) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction( function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( ( elem = temp[ i ] ) ) { matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) ) { // Restore matcherIn since elem is not yet a final match temp.push( ( matcherIn[ i ] = elem ) ); } } postFinder( null, ( matcherOut = [] ), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) && ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { seed[ temp ] = !( results[ temp ] = elem ); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } } ); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[ 0 ].type ], implicitRelative = leadingRelative || Expr.relative[ " " ], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( ( checkContext = context ).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[ j ].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens .slice( 0, i - 1 ) .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), len = elems.length; if ( outermost ) { // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq outermostContext = context == document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { if ( byElement && elem ) { j = 0; // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( !context && elem.ownerDocument != document ) { setDocument( elem ); xml = !documentIsHTML; } while ( ( matcher = elementMatchers[ j++ ] ) ) { if ( matcher( elem, context || document, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( ( elem = !matcher && elem ) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( ( matcher = setMatchers[ j++ ] ) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !( unmatched[ i ] || setMatched[ i ] ) ) { setMatched[ i ] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[ i ] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( ( selector = compiled.selector || selector ) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[ 0 ] = match[ 0 ].slice( 0 ); if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { context = ( Expr.find[ "ID" ]( token.matches[ 0 ] .replace( runescape, funescape ), context ) || [] )[ 0 ]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[ i ]; // Abort if we hit a combinator if ( Expr.relative[ ( type = token.type ) ] ) { break; } if ( ( find = Expr.find[ type ] ) ) { // Search, expanding context for leading sibling combinators if ( ( seed = find( token.matches[ 0 ].replace( runescape, funescape ), rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || context ) ) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert( function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; } ); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert( function( el ) { el.innerHTML = ""; return el.firstChild.getAttribute( "href" ) === "#"; } ) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } } ); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert( function( el ) { el.innerHTML = ""; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; } ) ) { addHandle( "value", function( elem, _name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } ); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert( function( el ) { return el.getAttribute( "disabled" ) == null; } ) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; } } ); } return Sizzle; } )( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; jQuery.escapeSelector = Sizzle.escape; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; function nodeName( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Filtered directly for both simple and complex selectors return jQuery.filter( qualifier, elements, not ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } if ( elems.length === 1 && elem.nodeType === 1 ) { return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; } return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret, len = this.length, self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } ret = this.pushStack( [] ); for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } return len > 1 ? jQuery.uniqueSort( ret ) : ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], targets = typeof selectors !== "string" && jQuery( selectors ); // Positional selectors never match, since there's no _selection_ context if ( !rneedsContext.test( selectors ) ) { for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( targets ? targets.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, _i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, _i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, _i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { if ( elem.contentDocument != null && // Support: IE 11+ // elements with no `data` attribute has an object // `contentDocument` with a `null` prototype. getProto( elem.contentDocument ) ) { return elem.contentDocument; } // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only // Treat the template element as a regular one in browsers that // don't support it. if ( nodeName( elem, "template" ) ) { elem = elem.content || elem; } return jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = locked || options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && toType( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; function Identity( v ) { return v; } function Thrower( ex ) { throw ex; } function adoptValue( value, resolve, reject, noValue ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: // * false: [ value ].slice( 0 ) => resolve( value ) // * true: [ value ].slice( 1 ) => resolve() resolve.apply( undefined, [ value ].slice( noValue ) ); } // For Promises/A+, convert exceptions into rejections // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in // Deferred#then to conditionally suppress rejection. } catch ( value ) { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context reject.apply( undefined, [ value ] ); } } jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, callbacks, // ... .then handlers, argument index, [final state] [ "notify", "progress", jQuery.Callbacks( "memory" ), jQuery.Callbacks( "memory" ), 2 ], [ "resolve", "done", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, "catch": function( fn ) { return promise.then( null, fn ); }, // Keep pipe for back-compat pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( _i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; // deferred.progress(function() { bind to newDefer or newDefer.notify }) // deferred.done(function() { bind to newDefer or newDefer.resolve }) // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, then: function( onFulfilled, onRejected, onProgress ) { var maxDepth = 0; function resolve( depth, deferred, handler, special ) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; // Support: Promises/A+ section 2.3.3.3.3 // https://promisesaplus.com/#point-59 // Ignore double-resolution attempts if ( depth < maxDepth ) { return; } returned = handler.apply( that, args ); // Support: Promises/A+ section 2.3.1 // https://promisesaplus.com/#point-48 if ( returned === deferred.promise() ) { throw new TypeError( "Thenable self-resolution" ); } // Support: Promises/A+ sections 2.3.3.1, 3.5 // https://promisesaplus.com/#point-54 // https://promisesaplus.com/#point-75 // Retrieve `then` only once then = returned && // Support: Promises/A+ section 2.3.4 // https://promisesaplus.com/#point-64 // Only check objects and functions for thenability ( typeof returned === "object" || typeof returned === "function" ) && returned.then; // Handle a returned thenable if ( isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ) ); // Normal processors (resolve) also hook into progress } else { // ...and disregard older resolution values maxDepth++; then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ), resolve( maxDepth, deferred, Identity, deferred.notifyWith ) ); } // Handle all other returned values } else { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Identity ) { that = undefined; args = [ returned ]; } // Process the value(s) // Default process is resolve ( special || deferred.resolveWith )( that, args ); } }, // Only normal processors (resolve) catch and reject exceptions process = special ? mightThrow : function() { try { mightThrow(); } catch ( e ) { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, process.stackTrace ); } // Support: Promises/A+ section 2.3.3.3.4.1 // https://promisesaplus.com/#point-61 // Ignore post-resolution exceptions if ( depth + 1 >= maxDepth ) { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Thrower ) { that = undefined; args = [ e ]; } deferred.rejectWith( that, args ); } } }; // Support: Promises/A+ section 2.3.3.3.1 // https://promisesaplus.com/#point-57 // Re-resolve promises immediately to dodge false rejection from // subsequent errors if ( depth ) { process(); } else { // Call an optional hook to record the stack, in case of exception // since it's otherwise lost when execution goes async if ( jQuery.Deferred.getStackHook ) { process.stackTrace = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } }; } return jQuery.Deferred( function( newDefer ) { // progress_handlers.add( ... ) tuples[ 0 ][ 3 ].add( resolve( 0, newDefer, isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, isFunction( onRejected ) ? onRejected : Thrower ) ); } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 5 ]; // promise.progress = list.add // promise.done = list.add // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = "resolved" (i.e., fulfilled) // state = "rejected" state = stateString; }, // rejected_callbacks.disable // fulfilled_callbacks.disable tuples[ 3 - i ][ 2 ].disable, // rejected_handlers.disable // fulfilled_handlers.disable tuples[ 3 - i ][ 3 ].disable, // progress_callbacks.lock tuples[ 0 ][ 2 ].lock, // progress_handlers.lock tuples[ 0 ][ 3 ].lock ); } // progress_handlers.fire // fulfilled_handlers.fire // rejected_handlers.fire list.add( tuple[ 3 ].fire ); // deferred.notify = function() { deferred.notifyWith(...) } // deferred.resolve = function() { deferred.resolveWith(...) } // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; // deferred.notifyWith = list.fireWith // deferred.resolveWith = list.fireWith // deferred.rejectWith = list.fireWith deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( singleValue ) { var // count of uncompleted subordinates remaining = arguments.length, // count of unprocessed arguments i = remaining, // subordinate fulfillment data resolveContexts = Array( i ), resolveValues = slice.call( arguments ), // the master Deferred master = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { return function( value ) { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { master.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, !remaining ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } return master.promise(); } } ); // These usually indicate a programmer mistake during development, // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function( error, stack ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); } }; jQuery.readyException = function( error ) { window.setTimeout( function() { throw error; } ); }; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList .then( fn ) // Wrap jQuery.readyException in a function so that the lookup // happens at the time of error handling instead of callback // registration. .catch( function( error ) { jQuery.readyException( error ); } ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( toType( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, _key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } if ( chainable ) { return elems; } // Gets if ( bulk ) { return fn.call( elems ); } return len ? fn( elems[ 0 ], key ) : emptyGet; }; // Matches dashed string for camelizing var rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g; // Used by camelCase as callback to replace() function fcamelCase( _all, letter ) { return letter.toUpperCase(); } // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 15 // Microsoft forgot to hump their vendor prefix (#9572) function camelCase( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ camelCase( prop ) ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { return this.get( owner, key ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( Array.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( camelCase ); } else { key = camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnothtmlwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function getData( data ) { if ( data === "true" ) { return true; } if ( data === "false" ) { return false; } if ( data === "null" ) { return null; } // Only convert to a number if it doesn't change the string if ( data === +data + "" ) { return +data; } if ( rbrace.test( data ) ) { return JSON.parse( data ); } return data; } function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = getData( data ); } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || Array.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var documentElement = document.documentElement; var isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ); }, composed = { composed: true }; // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only // Check attachment across shadow DOM boundaries when possible (gh-3504) // Support: iOS 10.0-10.2 only // Early iOS 10 versions support `attachShadow` but not `getRootNode`, // leading to errors. We need to check for `getRootNode`. if ( documentElement.getRootNode ) { isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ) || elem.getRootNode( composed ) === elem.ownerDocument; }; } var isHiddenWithinTree = function( elem, el ) { // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; // Inline style trumps all return elem.style.display === "none" || elem.style.display === "" && // Otherwise, check computed style // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. isAttached( elem ) && jQuery.css( elem, "display" ) === "none"; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = elem.nodeType && ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Support: Firefox <=54 // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) initial = initial / 2; // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; while ( maxIterations-- ) { // Evaluate and update our best guess (doubling guesses that zero out). // Finish if the scale equals or crosses 1 (making the old*new product non-positive). jQuery.style( elem, prop, initialInUnit + unit ); if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { maxIterations = 0; } initialInUnit = initialInUnit / scale; } initialInUnit = initialInUnit * 2; jQuery.style( elem, prop, initialInUnit + unit ); // Make sure we update the tween properties later on valueParts = valueParts || []; } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ); display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // Support: IE <=9 only // IE <=9 replaces "; support.option = !!div.lastChild; } )(); // We have to close these tags to support XHTML (#13200) var wrapMap = { // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting or other required elements. thead: [ 1, "", "
" ], col: [ 2, "", "
" ], tr: [ 2, "", "
" ], td: [ 3, "", "
" ], _default: [ 0, "", "" ] }; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: IE <=9 only if ( !support.option ) { wrapMap.optgroup = wrapMap.option = [ 1, "" ]; } function getAll( context, tag ) { // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret; if ( typeof context.getElementsByTagName !== "undefined" ) { ret = context.getElementsByTagName( tag || "*" ); } else if ( typeof context.querySelectorAll !== "undefined" ) { ret = context.querySelectorAll( tag || "*" ); } else { ret = []; } if ( tag === undefined || tag && nodeName( context, tag ) ) { return jQuery.merge( [ context ], ret ); } return ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, attached, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( toType( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } attached = isAttached( elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( attached ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 - 11+ // focus() and blur() are asynchronous, except when they are no-op. // So expect focus to be synchronous when the element is already active, // and blur to be synchronous when the element is not already active. // (focus and blur are always synchronous in other supported browsers, // this just defines when we can count on it). function expectSync( elem, type ) { return ( elem === safeActiveElement() ) === ( type === "focus" ); } // Support: IE <=9 only // Accessing document.activeElement can throw unexpectedly // https://bugs.jquery.com/ticket/13393 function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Only attach events to objects that accept data if ( !acceptData( elem ) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Ensure that invalid selectors throw exceptions at attach time // Evaluate against documentElement in case elem is a non-element node (e.g., document) if ( selector ) { jQuery.find.matchesSelector( documentElement, selector ); } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = Object.create( null ); } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( nativeEvent ) { var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( nativeEvent ), handlers = ( dataPriv.get( this, "events" ) || Object.create( null ) )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; for ( i = 1; i < arguments.length; i++ ) { args[ i ] = arguments[ i ]; } event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // If the event is namespaced, then each handler is only invoked if it is // specially universal or its namespaces are a superset of the event's. if ( !event.rnamespace || handleObj.namespace === false || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers if ( delegateCount && // Support: IE <=9 // Black-hole SVG instance trees (trac-13180) cur.nodeType && // Support: Firefox <=42 // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click // Support: IE 11 only // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) !( event.type === "click" && event.button >= 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { matchedHandlers = []; matchedSelectors = {}; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matchedSelectors[ sel ] === undefined ) { matchedSelectors[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matchedSelectors[ sel ] ) { matchedHandlers.push( handleObj ); } } if ( matchedHandlers.length ) { handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); } } } } // Add the remaining (directly-bound) handlers cur = this; if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, addProp: function( name, hook ) { Object.defineProperty( jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { return this.originalEvent[ name ]; } }, set: function( value ) { Object.defineProperty( this, name, { enumerable: true, configurable: true, writable: true, value: value } ); } } ); }, fix: function( originalEvent ) { return originalEvent[ jQuery.expando ] ? originalEvent : new jQuery.Event( originalEvent ); }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // Utilize native event to ensure correct state for checkable inputs setup: function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Claim the first handler if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { // dataPriv.set( el, "click", ... ) leverageNative( el, "click", returnTrue ); } // Return false to allow normal processing in the caller return false; }, trigger: function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Force setup before triggering a click if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { leverageNative( el, "click" ); } // Return non-false to allow normal event-path propagation return true; }, // For cross-browser consistency, suppress native .click() on links // Also prevent it if we're currently inside a leveraged native-event stack _default: function( event ) { var target = event.target; return rcheckableType.test( target.type ) && target.click && nodeName( target, "input" ) && dataPriv.get( target, "click" ) || nodeName( target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; // Ensure the presence of an event listener that handles manually-triggered // synthetic events by interrupting progress until reinvoked in response to // *native* events that it fires directly, ensuring that state changes have // already occurred before other listeners are invoked. function leverageNative( el, type, expectSync ) { // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add if ( !expectSync ) { if ( dataPriv.get( el, type ) === undefined ) { jQuery.event.add( el, type, returnTrue ); } return; } // Register the controller as a special universal handler for all event namespaces dataPriv.set( el, type, false ); jQuery.event.add( el, type, { namespace: false, handler: function( event ) { var notAsync, result, saved = dataPriv.get( this, type ); if ( ( event.isTrigger & 1 ) && this[ type ] ) { // Interrupt processing of the outer synthetic .trigger()ed event // Saved data should be false in such cases, but might be a leftover capture object // from an async native handler (gh-4350) if ( !saved.length ) { // Store arguments for use when handling the inner native event // There will always be at least one argument (an event object), so this array // will not be confused with a leftover capture object. saved = slice.call( arguments ); dataPriv.set( this, type, saved ); // Trigger the native event and capture its result // Support: IE <=9 - 11+ // focus() and blur() are asynchronous notAsync = expectSync( this, type ); this[ type ](); result = dataPriv.get( this, type ); if ( saved !== result || notAsync ) { dataPriv.set( this, type, false ); } else { result = {}; } if ( saved !== result ) { // Cancel the outer synthetic event event.stopImmediatePropagation(); event.preventDefault(); return result.value; } // If this is an inner synthetic event for an event with a bubbling surrogate // (focus or blur), assume that the surrogate already propagated from triggering the // native event and prevent that from happening again here. // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the // bubbling surrogate propagates *after* the non-bubbling base), but that seems // less bad than duplication. } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { event.stopPropagation(); } // If this is a native event triggered above, everything is now in order // Fire an inner synthetic event with the original arguments } else if ( saved.length ) { // ...and capture the result dataPriv.set( this, type, { value: jQuery.event.trigger( // Support: IE <=9 - 11+ // Extend with the prototype to reset the above stopImmediatePropagation() jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), saved.slice( 1 ), this ) } ); // Abort handling of the native event event.stopImmediatePropagation(); } } } ); } jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; // Create target properties // Support: Safari <=6 - 7 only // Target should not be a text node (#504, #13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || Date.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Includes all common event props including KeyEvent and MouseEvent specific props jQuery.each( { altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, code: true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: function( event ) { var button = event.button; // Add which for key events if ( event.which == null && rkeyEvent.test( event.type ) ) { return event.charCode != null ? event.charCode : event.keyCode; } // Add which for click: 1 === left; 2 === middle; 3 === right if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { if ( button & 1 ) { return 1; } if ( button & 2 ) { return 3; } if ( button & 4 ) { return 2; } return 0; } return event.which; } }, jQuery.event.addProp ); jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { jQuery.event.special[ type ] = { // Utilize native event if possible so blur/focus sequence is correct setup: function() { // Claim the first handler // dataPriv.set( this, "focus", ... ) // dataPriv.set( this, "blur", ... ) leverageNative( this, type, expectSync ); // Return false to allow normal processing in the caller return false; }, trigger: function() { // Force setup before trigger leverageNative( this, type ); // Return non-false to allow normal event-path propagation return true; }, delegateType: delegateType }; } ); // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var // Support: IE <=10 - 11, Edge 12 - 13 only // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /\s*$/g; // Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { if ( nodeName( elem, "table" ) && nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return jQuery( elem ).children( "tbody" )[ 0 ] || elem; } return elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { elem.type = elem.type.slice( 5 ); } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.get( src ); events = pdataOld.events; if ( events ) { dataPriv.remove( dest, "handle events" ); for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = flat( args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], valueIsFunction = isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( valueIsFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( valueIsFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl && !node.noModule ) { jQuery._evalUrl( node.src, { nonce: node.nonce || node.getAttribute( "nonce" ) }, doc ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && isAttached( node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html; }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = isAttached( elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: Android <=4.0 only, PhantomJS 1 only // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE <=11 only, Firefox <=30 (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; var swap = function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); ( function() { // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { // This is a singleton, we need to execute it only once if ( !div ) { return; } container.style.cssText = "position:absolute;left:-11111px;width:60px;" + "margin-top:1px;padding:0;border:0"; div.style.cssText = "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + "margin:auto;border:1px;padding:1px;" + "width:60%;top:1%"; documentElement.appendChild( container ).appendChild( div ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 // Some styles come back with percentage values, even though they shouldn't div.style.right = "60%"; pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; // Support: IE 9 - 11 only // Detect misreporting of content dimensions for box-sizing:border-box elements boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; // Support: IE 9 only // Detect overflow:scroll screwiness (gh-3699) // Support: Chrome <=64 // Don't get tricked when zoom affects offsetWidth (gh-4029) div.style.position = "absolute"; scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; documentElement.removeChild( container ); // Nullify the div so it wouldn't be stored in the memory and // it will also be a sign that checks already performed div = null; } function roundPixelMeasures( measure ) { return Math.round( parseFloat( measure ) ); } var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, reliableTrDimensionsVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE <=9 - 11 only // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; jQuery.extend( support, { boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelBoxStyles: function() { computeStyleTests(); return pixelBoxStylesVal; }, pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; }, scrollboxSize: function() { computeStyleTests(); return scrollboxSizeVal; }, // Support: IE 9 - 11+, Edge 15 - 18+ // IE/Edge misreport `getComputedStyle` of table rows with width/height // set in CSS while `offset*` properties report correct values. // Behavior in IE 9 is more subtle than in newer versions & it passes // some versions of this test; make sure not to make it pass there! reliableTrDimensions: function() { var table, tr, trChild, trStyle; if ( reliableTrDimensionsVal == null ) { table = document.createElement( "table" ); tr = document.createElement( "tr" ); trChild = document.createElement( "div" ); table.style.cssText = "position:absolute;left:-11111px"; tr.style.height = "1px"; trChild.style.height = "9px"; documentElement .appendChild( table ) .appendChild( tr ) .appendChild( trChild ); trStyle = window.getComputedStyle( tr ); reliableTrDimensionsVal = parseInt( trStyle.height ) > 3; documentElement.removeChild( table ); } return reliableTrDimensionsVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, // Support: Firefox 51+ // Retrieving style before computed somehow // fixes an issue with getting wrong values // on detached elements style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is needed for: // .css('filter') (IE 9 only, #12537) // .css('--customProperty) (#3144) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !isAttached( elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE <=9 - 11 only // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style, vendorProps = {}; // Return a vendor-prefixed property or undefined function vendorPropName( name ) { // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } // Return a potentially-mapped jQuery.cssProps or vendor prefixed property function finalPropName( name ) { var final = jQuery.cssProps[ name ] || vendorProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return vendorProps[ name ] = vendorPropName( name ) || name; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rcustomProp = /^--/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }; function setPositiveNumber( _elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { var i = dimension === "width" ? 1 : 0, extra = 0, delta = 0; // Adjustment may not be necessary if ( box === ( isBorderBox ? "border" : "content" ) ) { return 0; } for ( ; i < 4; i += 2 ) { // Both box models exclude margin if ( box === "margin" ) { delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); } // If we get here with a content-box, we're seeking "padding" or "border" or "margin" if ( !isBorderBox ) { // Add padding delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // For "border" or "margin", add border if ( box !== "padding" ) { delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); // But still keep track of it otherwise } else { extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } // If we get here with a border-box (content + padding + border), we're seeking "content" or // "padding" or "margin" } else { // For "content", subtract padding if ( box === "content" ) { delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // For "content" or "padding", subtract border if ( box !== "margin" ) { delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } // Account for positive content-box scroll gutter when requested by providing computedVal if ( !isBorderBox && computedVal >= 0 ) { // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border // Assuming integer scroll gutter, subtract the rest and round down delta += Math.max( 0, Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - computedVal - delta - extra - 0.5 // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter // Use an explicit zero to avoid NaN (gh-3964) ) ) || 0; } return delta; } function getWidthOrHeight( elem, dimension, extra ) { // Start with computed style var styles = getStyles( elem ), // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). // Fake content-box until we know it's needed to know the true value. boxSizingNeeded = !support.boxSizingReliable() || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", valueIsBorderBox = isBorderBox, val = curCSS( elem, dimension, styles ), offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); // Support: Firefox <=54 // Return a confounding non-pixel value or feign ignorance, as appropriate. if ( rnumnonpx.test( val ) ) { if ( !extra ) { return val; } val = "auto"; } // Support: IE 9 - 11 only // Use offsetWidth/offsetHeight for when box sizing is unreliable. // In those cases, the computed value can be trusted to be border-box. if ( ( !support.boxSizingReliable() && isBorderBox || // Support: IE 10 - 11+, Edge 15 - 18+ // IE/Edge misreport `getComputedStyle` of table rows with width/height // set in CSS while `offset*` properties report correct values. // Interestingly, in some cases IE 9 doesn't suffer from this issue. !support.reliableTrDimensions() && nodeName( elem, "tr" ) || // Fall back to offsetWidth/offsetHeight when value is "auto" // This happens for inline elements with no explicit setting (gh-3571) val === "auto" || // Support: Android <=4.1 - 4.3 only // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && // Make sure the element is visible & connected elem.getClientRects().length ) { isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Where available, offsetWidth/offsetHeight approximate border box dimensions. // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the // retrieved value as a content box dimension. valueIsBorderBox = offsetProp in elem; if ( valueIsBorderBox ) { val = elem[ offsetProp ]; } } // Normalize "" and auto val = parseFloat( val ) || 0; // Adjust for the element's box model return ( val + boxModelAdjustment( elem, dimension, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles, // Provide the current computed size to request scroll gutter calculation (gh-3589) val ) ) + "px"; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "gridArea": true, "gridColumn": true, "gridColumnEnd": true, "gridColumnStart": true, "gridRow": true, "gridRowEnd": true, "gridRowStart": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: {}, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = camelCase( name ), isCustomProp = rcustomProp.test( name ), style = elem.style; // Make sure that we're working with the right name. We don't // want to query the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append // "px" to a few hardcoded values. if ( type === "number" && !isCustomProp ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { if ( isCustomProp ) { style.setProperty( name, value ); } else { style[ name ] = value; } } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = camelCase( name ), isCustomProp = rcustomProp.test( name ); // Make sure that we're working with the right name. We don't // want to modify the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( _i, dimension ) { jQuery.cssHooks[ dimension ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && // Support: Safari 8+ // Table columns in Safari have non-zero offsetWidth & zero // getBoundingClientRect().width unless display is changed. // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, dimension, extra ); } ) : getWidthOrHeight( elem, dimension, extra ); } }, set: function( elem, value, extra ) { var matches, styles = getStyles( elem ), // Only read styles.position if the test has a chance to fail // to avoid forcing a reflow. scrollboxSizeBuggy = !support.scrollboxSize() && styles.position === "absolute", // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) boxSizingNeeded = scrollboxSizeBuggy || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", subtract = extra ? boxModelAdjustment( elem, dimension, extra, isBorderBox, styles ) : 0; // Account for unreliable border-box dimensions by comparing offset* to computed and // faking a content-box to get border and padding (gh-3699) if ( isBorderBox && scrollboxSizeBuggy ) { subtract -= Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - parseFloat( styles[ dimension ] ) - boxModelAdjustment( elem, dimension, "border", false, styles ) - 0.5 ); } // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ dimension ] = value; value = jQuery.css( elem, dimension ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( prefix !== "margin" ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( Array.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); } } ); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( jQuery.cssHooks[ tween.prop ] || tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 only // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back compat <1.8 extension point jQuery.fx.step = {}; var fxNow, inProgress, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function schedule() { if ( inProgress ) { if ( document.hidden === false && window.requestAnimationFrame ) { window.requestAnimationFrame( schedule ); } else { window.setTimeout( schedule, jQuery.fx.interval ); } jQuery.fx.tick(); } } // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = Date.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Queue-skipping animations hijack the fx hooks if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Detect show/hide animations for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.test( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // Pretend to be hidden if this is a "show" and // there is still data from a stopped show/hide if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; // Ignore all other no-op show/hide data } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } // Bail out if this is a no-op like .hide().hide() propTween = !jQuery.isEmptyObject( props ); if ( !propTween && jQuery.isEmptyObject( orig ) ) { return; } // Restrict "overflow" and "display" styles during box animations if ( isBox && elem.nodeType === 1 ) { // Support: IE <=9 - 11, Edge 12 - 15 // Record all 3 overflow attributes because IE does not infer the shorthand // from identically-valued overflowX and overflowY and Edge just mirrors // the overflowX value there. opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Identify a display type, preferring old show/hide data over the CSS cascade restoreDisplay = dataShow && dataShow.display; if ( restoreDisplay == null ) { restoreDisplay = dataPriv.get( elem, "display" ); } display = jQuery.css( elem, "display" ); if ( display === "none" ) { if ( restoreDisplay ) { display = restoreDisplay; } else { // Get nonempty value(s) by temporarily forcing visibility showHide( [ elem ], true ); restoreDisplay = elem.style.display || restoreDisplay; display = jQuery.css( elem, "display" ); showHide( [ elem ] ); } } // Animate inline elements as inline-block if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { if ( jQuery.css( elem, "float" ) === "none" ) { // Restore the original display value at the end of pure show/hide animations if ( !propTween ) { anim.done( function() { style.display = restoreDisplay; } ); if ( restoreDisplay == null ) { display = style.display; restoreDisplay = display === "none" ? "" : display; } } style.display = "inline-block"; } } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // Implement show/hide animations propTween = false; for ( prop in orig ) { // General show/hide setup for this element animation if ( !propTween ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); } // Store hidden/visible for toggle so `.stop().toggle()` "reverses" if ( toggle ) { dataShow.hidden = !hidden; } // Show elements before animating them if ( hidden ) { showHide( [ elem ], true ); } /* eslint-disable no-loop-func */ anim.done( function() { /* eslint-enable no-loop-func */ // The final step of a "hide" animation is actually hiding the element if ( !hidden ) { showHide( [ elem ] ); } dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); } // Per-property setup propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = propTween.start; if ( hidden ) { propTween.end = propTween.start; propTween.start = 0; } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( Array.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 only // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); // If there's more to do, yield if ( percent < 1 && length ) { return remaining; } // If this was an empty animation, synthesize a final progress notification if ( !length ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); } // Resolve the animation and report its conclusion deferred.resolveWith( elem, [ animation ] ); return false; }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = result.stop.bind( result ); } return result; } } jQuery.map( props, createTween, animation ); if ( isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } // Attach callbacks from options animation .progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); return animation; } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnothtmlwhite ); } var prop, index = 0, length = props.length; for ( ; index < length; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !isFunction( easing ) && easing }; // Go to the end state if fx are off if ( jQuery.fx.off ) { opt.duration = 0; } else { if ( typeof opt.duration !== "number" ) { if ( opt.duration in jQuery.fx.speeds ) { opt.duration = jQuery.fx.speeds[ opt.duration ]; } else { opt.duration = jQuery.fx.speeds._default; } } } // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = Date.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Run the timer and safely remove it when done (allowing for external removal) if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); jQuery.fx.start(); }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( inProgress ) { return; } inProgress = true; schedule(); }; jQuery.fx.stop = function() { inProgress = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: Android <=4.3 only // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE <=11 only // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: IE <=11 only // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, // Attribute names can contain non-HTML whitespace characters // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 attrNames = value && value.match( rnothtmlwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); if ( tabindex ) { return parseInt( tabindex, 10 ); } if ( rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ) { return 0; } return -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup // eslint rule "no-unused-expressions" is disabled for this code // since it considers such accessions noop if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); // Strip and collapse whitespace according to HTML spec // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); } function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } function classesToArray( value ) { if ( Array.isArray( value ) ) { return value; } if ( typeof value === "string" ) { return value.match( rnothtmlwhite ) || []; } return []; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } classes = classesToArray( value ); if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } classes = classesToArray( value ); if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isValidValue = type === "string" || Array.isArray( value ); if ( typeof stateVal === "boolean" && isValidValue ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( isValidValue ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = classesToArray( value ); while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, valueIsFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; // Handle most common string cases if ( typeof ret === "string" ) { return ret.replace( rreturn, "" ); } // Handle cases where value is null/undef or number return ret == null ? "" : ret; } return; } valueIsFunction = isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( valueIsFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( Array.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE <=10 - 11 only // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace stripAndCollapse( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, i, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length; if ( index < 0 ) { i = max; } else { i = one ? index : 0; } // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // Support: IE <=9 only // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && ( !option.parentNode.disabled || !nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; /* eslint-disable no-cond-assign */ if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } /* eslint-enable no-cond-assign */ } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( Array.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion support.focusin = "onfocusin" in window; var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, stopPropagationCallback = function( e ) { e.stopPropagation(); }; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = lastElement = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { lastElement = cur; event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; if ( event.isPropagationStopped() ) { lastElement.addEventListener( type, stopPropagationCallback ); } elem[ type ](); if ( event.isPropagationStopped() ) { lastElement.removeEventListener( type, stopPropagationCallback ); } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { // Handle: regular nodes (via `this.ownerDocument`), window // (via `this.document`) & document (via `this`). var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var location = window.location; var nonce = { guid: Date.now() }; var rquery = ( /\?/ ); // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; if ( !data || typeof data !== "string" ) { return null; } // Support: IE 9 - 11 only // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( Array.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && toType( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, valueOrFunction ) { // If value is a function, invoke it and use its return value var value = isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; if ( a == null ) { return ""; } // If an array was passed in, assume that it is an array of form elements. if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ) .filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ) .map( function( _i, elem ) { var val = jQuery( this ).val(); if ( val == null ) { return null; } if ( Array.isArray( val ) ) { return jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ); } return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; if ( isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": JSON.parse, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // Request state (becomes false upon send and true upon completion) completed, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // uncached part of the url uncached, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( completed ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[ 1 ].toLowerCase() + " " ] = ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) .concat( match[ 2 ] ); } } match = responseHeaders[ key.toLowerCase() + " " ]; } return match == null ? null : match.join( ", " ); }, // Raw string getAllResponseHeaders: function() { return completed ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { if ( completed == null ) { name = requestHeadersNames[ name.toLowerCase() ] = requestHeadersNames[ name.toLowerCase() ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( completed == null ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( completed ) { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } else { // Lazy-add the new callbacks in a way that preserves old ones for ( code in map ) { statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE <=8 - 11, Edge 12 - 15 // IE throws exception on accessing the href property if url is malformed, // e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE <=8 - 11 only // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( completed ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on // Remove hash to simplify url manipulation cacheURL = s.url.replace( rhash, "" ); // More options handling for requests with no content if ( !s.hasContent ) { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); // If data is available and should be processed, append data to url if ( s.data && ( s.processData || typeof s.data === "string" ) ) { cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add or update anti-cache param if needed if ( s.cache === false ) { cacheURL = cacheURL.replace( rantiCache, "$1" ); uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + uncached; } // Put hash and anti-cache on the URL that will be requested (gh-1732) s.url = cacheURL + uncached; // Change '%20' to '+' if this is encoded form body content (gh-2658) } else if ( s.data && s.processData && ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { s.data = s.data.replace( r20, "+" ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds completeDeferred.add( s.complete ); jqXHR.done( s.success ); jqXHR.fail( s.error ); // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( completed ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { completed = false; transport.send( requestHeaders, done ); } catch ( e ) { // Rethrow post-completion exceptions if ( completed ) { throw e; } // Propagate others as results done( -1, e ); } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Ignore repeat invocations if ( completed ) { return; } completed = true; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Use a noop converter for missing script if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) { s.converters[ "text script" ] = function() {}; } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( _i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery.ajaxPrefilter( function( s ) { var i; for ( i in s.headers ) { if ( i.toLowerCase() === "content-type" ) { s.contentType = s.headers[ i ] || ""; } } } ); jQuery._evalUrl = function( url, options, doc ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", cache: true, async: false, global: false, // Only evaluate the response if it is successful (gh-4126) // dataFilter is not invoked for failure responses, so using it instead // of the default converter is kludgy but it works. converters: { "text script": function() {} }, dataFilter: function( response ) { jQuery.globalEval( response, options, doc ); } } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( isFunction( html ) ) { html = html.call( this[ 0 ] ); } // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var htmlIsFunction = isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); jQuery.expr.pseudos.hidden = function( elem ) { return !jQuery.expr.pseudos.visible( elem ); }; jQuery.expr.pseudos.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; jQuery.ajaxSettings.xhr = function() { try { return new window.XMLHttpRequest(); } catch ( e ) {} }; var xhrSuccessStatus = { // File protocol always yields status code 0, assume 200 0: 200, // Support: IE <=9 only // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport( function( options ) { var callback, errorCallback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.ontimeout = xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { // Support: IE <=9 only // On a manual native abort, IE9 throws // errors on any property access that is not readyState if ( typeof xhr.status !== "number" ) { complete( 0, "error" ); } else { complete( // File: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE <=9 only // IE9 has no XHR2 but throws on binary (trac-11426) // For XHR2 non-text, let the caller handle it (gh-2498) ( xhr.responseType || "text" ) !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); // Support: IE 9 only // Use onreadystatechange to replace onabort // to handle uncaught aborts if ( xhr.onabort !== undefined ) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { // Check readyState before timeout as it changes if ( xhr.readyState === 4 ) { // Allow onerror to be called first, // but that will not handle a native abort // Also, save errorCallback to a variable // as xhr.onerror cannot be accessed window.setTimeout( function() { if ( callback ) { errorCallback(); } } ); } }; } // Create the abort callback callback = callback( "abort" ); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } } ); // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) jQuery.ajaxPrefilter( function( s ) { if ( s.crossDomain ) { s.contents.script = false; } } ); // Install script dataType jQuery.ajaxSetup( { accepts: { script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } } ); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain or forced-by-attrs requests if ( s.crossDomain || s.scriptAttrs ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "`) const artist = wand.artist wand.extra.winDim = [artist.use.width, artist.use.height] const test = wand.test const routes = { 'test.html': artist.share.testArtist, 'test_basic.html': artist.share.testBasic, 'empty.html': () => console.log('empty page/canvas'), '': () => console.log('homepage'), 'plot.html': test.testPlot, 'diffusion.html': test.testDiffusion, 'multilevelDiffusion.html': test.testMultilevelDiffusion, // fixme: add MultilevelDiffusionSketch or migrate it to netscience/meta.js 'metaNetwork.html': test.testMetaNetwork, 'rotate.html': test.testRotateLayouts, 'blink.html': test.testBlink, 'exhibit1.html': test.testExibition1, 'sparkmin.html': test.testSparkMin, 'losd.html': test.testSparkLosd, 'getNet.html': test.testGetNet0, 'getNet1.html': test.testGetNet1, 'getNet2.html': test.testGetNet2, 'getNet3.html': test.testGetNet3, 'mong.html': test.testMong, 'mongIO.html': test.testMongIO, 'mongNetIO.html': test.testMongNetIO, 'mongNetIO2.html': test.testMongBetterNetIO, 'netIO.html': test.testNetIO, 'gui.html': test.testGUI, 'guiMin.html': test.testNetUpload, 'guiMin2.html': test.testNetUpload2, 'netPage.html': test.testNetPage, 'puxi.html': test.testPuxi, 'h.html': test.testHtmlEls, 'h2.html': test.testHtmlEls2, 'gradus.html': test.testGradus, 'adParnassum.html': test.testAdParnassum, 'worldProperty.html': test.testWorldPropertyPage, 'jquery.html': test.testJQueryFontsAwesome, 'obj.html': test.testObj, 'colors.html': test.testColors, 'music.html': test.testMusic, 'looper.html': test.testLooper, 'seq.html': test.testSeq, 'sync.html': test.testSync, 'pat.html': test.testPattern, 'rec.html': test.testRec, 'rec2.html': test.testRec2, 'recCanvas.html': test.testRecCanvas, 'recAudio.html': test.testRecAudio, 'recAudioAndCanvas.html': test.testRecAudioAndCanvas, 'recAudioAndCanvas2.html': test.testRecAudioAndCanvas2, 'diffusionLimited.html': test.testDiffusionLimited, 'data_donated.html': () => console.log('a summary of the data donated in usage, upload and scrapping') } const _router = new wand.router.use.Router(routes) _router.loadCurrent() wand._router = _router },{"./modules/artist.js":400,"./modules/conductor.js":409,"./modules/maestro/all.js":421,"./modules/networks.js":430,"./modules/router.js":431,"./modules/transfer/main.js":433,"./modules/utils.js":438,"./test.js":439,"jquery":116}],400:[function(require,module,exports){ var draw = require('./drawing/main.js') const testArtist = () => { console.log(draw.use) draw.share.test.tests.backImage(draw.use.ambience, draw.share.base.PIXI, draw.share.base.app) draw.share.test.tests.particleSprites(draw.use.ambience, draw.share.base.PIXI, draw.share.base.app) draw.share.test.tests.panels(draw.use.ambience, draw.share.base.app) draw.share.test.tests.dancers(draw.use.ambience, draw.share.base.app) draw.share.test.tests.oneNode(draw.use) draw.share.test.tests.basicElements(draw.use) } const testBasic = () => { draw.share.test.tests.basicElements(draw.use) } module.exports = { use: draw.use, share: { draw: draw.share, testBasic, testArtist } } },{"./drawing/main.js":414}],401:[function(require,module,exports){ /* global performance, wand */ // this file holds helpers to enable animation const chooseUnique = require('../utils.js').chooseUnique const rotateLayouts = (drawnNet, app, artist, totalPositions = 300) => { const net = drawnNet.net let layouts = drawnNet.layouts window.lll = layouts layouts = Object.values(layouts) const movingProportion = 0.5 const nlayouts = layouts.length // per section, one section per layout ( == layout[x] -> layout[x+1]): const sectionPositions = totalPositions / nlayouts const movePositions = Math.floor(sectionPositions * movingProportion) const staticPositions = Math.floor(sectionPositions - movePositions) // there is one collection of sets of positions per node. // one set per layout, thus: // array[node][layout][position] = x, y const order = net.order const nodeLayoutPositions = [] for (let nodekey = 0; nodekey < order; nodekey++) { nodeLayoutPositions.push([]) for (let i = 0; i < nlayouts; i++) { const layout1 = layouts[i] const layout2 = layouts[(i + 1) % nlayouts] nodeLayoutPositions[nodekey].push([]) for (let j = 0; j < movePositions; j++) { const proportion = (movePositions - j) / movePositions const inverse = 1 - proportion const posx = proportion * layout1[nodekey].x + inverse * layout2[nodekey].x const posy = proportion * layout1[nodekey].y + inverse * layout2[nodekey].y nodeLayoutPositions[nodekey][i][j] = [posx, posy] } } } let positionCounter = 0 const sectionPositions_ = Math.floor(sectionPositions) let lock = false const anim = delta => { // delta is 1 for 60 fps const section = Math.floor(positionCounter / sectionPositions) const positionInSection = positionCounter % sectionPositions_ const ismoving = positionInSection > staticPositions if (ismoving) { const positionInMovement = positionInSection - staticPositions net.forEachNode((key, attr) => { attr.pixiElement.x = nodeLayoutPositions[key][section][positionInMovement][0] attr.pixiElement.y = nodeLayoutPositions[key][section][positionInMovement][1] // shake: // attr.pixiElement.x = attr.pixiElement.x + Math.random() * (Math.random() > 0.5 ? 1 : -1) // attr.pixiElement.y = attr.pixiElement.y + Math.random() * (Math.random() > 0.5 ? 1 : -1) // realtime: // const prop = positionInMovement / movePositions // attr.pixiElement.x = layouts[section][key].x * (1 - prop) + layouts[(section + 1) % nlayouts][key].x * prop // attr.pixiElement.y = layouts[section][key].y * (1 - prop) + layouts[(section + 1) % nlayouts][key].y * prop }) net.forEachEdge((key, attr) => { artist.use.updateLink(attr.pixiElement) }) lock = false } else { if (!lock) { net.forEachNode((key, attr) => { attr.pixiElement.x = layouts[section][key].x attr.pixiElement.y = layouts[section][key].y }) net.forEachEdge((key, attr) => { artist.use.updateLink(attr.pixiElement) }) lock = true } else { net.forEachNode((key, attr) => { // wiggle: attr.pixiElement.x = attr.pixiElement.x + Math.random() * (Math.random() > 0.5 ? 1 : -1) attr.pixiElement.y = attr.pixiElement.y + Math.random() * (Math.random() > 0.5 ? 1 : -1) }) net.forEachEdge((key, attr) => { artist.use.updateLink(attr.pixiElement) }) } } positionCounter++ positionCounter = positionCounter % totalPositions } app.ticker.add(anim) return anim } const blink = (net, app) => { const anim = delta => { // delta is 1 for 60 fps if (Math.random() < 0.7) { net.forEachNode((key, attr) => { if (Math.random() < 0.4) { attr.pixiElement.tint = 0xffffff * Math.random() attr.pixiElement.alpha = Math.random() } }) } } app.ticker.add(anim) return anim } function showMembers (net, artist, alternate = false) { net.forEachNode((key, attr) => { const text = artist.use.mkTextBetter({ text: attr.name, pos: [attr.pixiElement.x, attr.pixiElement.y], fontSize: 35 }) attr.textElement = text }) if (alternate) { wand.extra.namesAlpha = wand.magic.adParnassum.state.namesAlpha.current || 0.5 const colorLoop = delta => { // delta is 1 for 60 fps if (Math.random() < 0.1 && !wand.extra.showNameBlock) { net.forEachNode((key, attr) => { if ((Math.random() < 0.1) && !attr.colorBlocked) { // attr.textElement.tint = 0xffffff * Math.random() attr.textElement.alpha = wand.extra.namesAlpha * Math.random() } }) } } artist.share.draw.base.app.ticker.add(colorLoop) return colorLoop } } function showMembersAndBlink (net, artist, alternate = false) { // fixme: does not find the element to .scale(1) when network changes // fixme: not used or has a test net.forEachNode((key, attr) => { const text = artist.use.mkTextBetter({ text: attr.name, pos: [attr.pixiElement.x, attr.pixiElement.y], fontSize: 35 }) attr.textElement = text }) if (alternate) { const blinkMembers = delta => { // delta is 1 for 60 fps if (Math.random() < 0.1) { net.forEachNode((key, attr) => { if (Math.random() < 0.1 && !attr.blinking) { attr.blinking = true attr.textElement.tint = 0xffffff * Math.random() attr.textElement.alpha = Math.random() const color = attr.pixiElement.tint const now = performance.now() attr.pixiElement.scale.set(2) const id = setInterval(() => { if (!attr || !attr.pixiElement) { clearInterval(id) return } attr.pixiElement.tint = 0xffffff * Math.random() if (performance.now() - now > 500) { attr.pixiElement.tint = color attr.pixiElement.scale.set(1) delete attr.blinking clearInterval(id) } }, 100) window.iidd = id } }) } } artist.share.draw.base.app.ticker.add(blinkMembers) return blinkMembers } } function blinkChangeColorsAndSayNames () { // fixme: not used nor tested const { artist, currentNetwork } = wand const net = currentNetwork this.sayNames = (density = 0.1) => { const nodes = net.nodes() let speaker = new wand.maestro.synths.Speaker() artist.share.draw.base.app.ticker.add(delta => { // delta is 1 for 60 fps if (Math.random() < density) { if (!speaker.synth.speaking) { const node = chooseUnique(nodes, 1)[0] const name = net.getNodeAttribute(node, 'name') speaker = new wand.maestro.synths.Speaker() speaker.play(name) window.speaker = speaker const textElement = net.getNodeAttribute(node, 'textElement') const pixiElement = net.getNodeAttribute(node, 'pixiElement') textElement.tint = 0xffffff * Math.random() textElement.alpha = Math.random() textElement.visible = true const color = pixiElement.tint const now = performance.now() pixiElement.scale.set(2) const id = setInterval(() => { pixiElement.tint = 0xffffff * Math.random() if (performance.now() - now > 500) { pixiElement.tint = color pixiElement.scale.set(1) clearInterval(id) } }, 100) } else { net.forEachNode((key, attr) => { if (Math.random() < 0.1) { attr.textElement.tint = 0xffffff * Math.random() attr.textElement.alpha = Math.random() } }) } } }) } } const playProgression = (progression, funcs) => { // todo: implement // progression is an array of arrays of notes // iterate through progression applying each func in funcs } const playSets = (sets, funcs) => { // todo: implement // sets is an array of arrays of notes // apply funcs respectivelly to each array in sets } module.exports = { use: { rotateLayouts, blink, blinkChangeColorsAndSayNames, showMembersAndBlink, showMembers, playProgression, playSets } } },{"../utils.js":438}],402:[function(require,module,exports){ /* global wand */ // this file has basics for drawing a network, which includes obtaining layouts // import forceAtlas2 from 'graphology-layout-forceatlas2' const { random, circular } = require('graphology-layout') const forceAtlas2 = require('graphology-layout-forceatlas2') // todo: use this webworker to animate layout while changing settings: // todo: check implementation as web worker of the package to learn and explore: // const FA2Layout = require('graphology-layout-forceatlas2/worker') const scale = positions => { // scales force atlas 2 positions to [-1,1], compliant with builtin layouts const k = Object.values(positions) const kx = k.map(kk => kk.x) const ky = k.map(kk => kk.y) const maxx = Math.max(...kx) const minx = Math.min(...kx) const maxy = Math.max(...ky) const miny = Math.min(...ky) Object.keys(positions).forEach(key => { positions[key].x = (positions[key].x - minx) / (maxx - minx) positions[key].y = (positions[key].y - miny) / (maxy - miny) }) return positions } const makeLayouts = (net, wh, border) => { const random_ = random.assign(net) const saneSettings = forceAtlas2.inferSettings(net) const layouts = { random: random_, circular: circular(net, { center: 0.75, scale: 0.5 }), atlas: scale(forceAtlas2(net, // todo: explore settings to optimize and result enhancements: { iterations: 150, settings: saneSettings } )) } scaleLayoutsToCanvas(layouts, wh, border) return layouts } const scaleLayoutsToCanvas = (layouts, wh, border) => { const layoutNames = Object.keys(layouts) const nodes = Object.keys(layouts[layoutNames[0]]) const size = nodes.length const wh_ = wh.map(i => i * (1 - border)) const border_ = wh.map(i => i * border / 2) window.layouts = layouts for (let i = 0; i < layoutNames.length; i++) { const name = layoutNames[i] for (let j = 0; j < size; j++) { const pos = layouts[name][nodes[j]] const x = pos.x * wh_[0] + border_[0] + (wand.extra.winDim[0] - wh[0]) / 2 const y = pos.y * wh_[1] + border_[1] + (wand.extra.winDim[1] - wh[1]) / 2 layouts[name][nodes[j]].x = x layouts[name][nodes[j]].y = y } } } class DrawnNet { constructor (drawer, net, wh = [], layouts = [], border = 0.1) { if (wh.length === 0) { wh = wand.extra.winDim } if (layouts.length === 0) { layouts = makeLayouts(net, wh, border) } this._plot(net, drawer, layouts.atlas) console.log('net drawn') this.layouts = layouts this.net = net } remove () { this.net.forEachNode((n, a) => { a.pixiElement.destroy() // a.textElement.destroy() }) this.net.forEachEdge((n, a) => a.pixiElement.destroy()) } _plot (net, drawer, layout) { net.forEachNode((key, attr) => { const node = drawer.mkNode() node.x = layout[key].x node.y = layout[key].y attr.pixiElement = node }) net.forEachEdge((key, attr, source, target, sourceAttr, targetAttr) => { attr.pixiElement = drawer.mkLink( sourceAttr.pixiElement, targetAttr.pixiElement, 1, -1, 0xffff00 ) }) } } module.exports = { use: { DrawnNet } } },{"graphology-layout":79,"graphology-layout-forceatlas2":76}],403:[function(require,module,exports){ /* global wand */ // each gradus has: // a feature it enables // a condition to complete, which triggers its function Gradus (timeStreach = 1) { const $ = wand.$ const s = (v) => { return v * this.relativeSize } const setStage = () => { this.athing = 'yes' this.currentLevel = 0 this.relativeSize = 1 this.fontSize = 20 wand.artist.use.mkTextFancy('ad parnassum: > 1', [s(this.fontSize / 2), s(this.fontSize * 1.5)], s(this.fontSize), 0xffff00) this.setLevel() } this.setLevel = () => { console.log('level:', this.currentLevel) const p = this.fontSize / 2 this.gradusText = wand.artist.use.mkTextFancy(`gradus: ${this.currentLevel}`, [s(p), s(p)], s(this.fontSize)) } this.bumpLevel = () => { this.currentLevel++ this.gradusText.text = `gradus: ${this.currentLevel}` } this.achievements = [] this.allGradus = [ () => { console.log('gradus1') this.achievements.push('loaded page') wand.extra.exibition = wand.test.testExhibition1('gradus') wand.currentNetwork = wand.extra.exibition.drawnNet.net console.log(10000 * timeStreach, timeStreach, 'timeStreach') setTimeout(() => { this.bumpLevel() this.allGradus[this.currentLevel]() }, 10000 * timeStreach) }, () => { console.log('gradus1.1') const ibtn = $('').prop('title', 'show links') const vbtn = $('').prop('title', 'show nodes') ibtn.prependTo('body') vbtn.prependTo('body') wand.extra.counter = { edgesVisible: 0, nodesVisible: 0 } ibtn.on('click', () => { wand.currentNetwork.forEachEdge((e, a) => { a.pixiElement.visible = !a.pixiElement.visible }) wand.extra.counter.edgesVisible++ }) vbtn.on('click', () => { wand.currentNetwork.forEachNode((n, a) => { a.pixiElement.visible = !a.pixiElement.visible }) wand.extra.counter.nodesVisible++ }) const condition = () => { setTimeout(() => { if (wand.extra.counter.nodesVisible >= 2 && wand.extra.counter.edgesVisible >= 2) { this.bumpLevel() this.allGradus[this.currentLevel]() return } condition() }, 300) } condition() }, () => { console.log('gradus2') wand.transfer.mong.findAllNetworks().then(r => { this.achievements.push('loaded data') this.bumpLevel() this.allGradus[this.currentLevel](r) }) }, (r) => { wand.extra.counter.networksVisualized = 0 wand.extra.counter.namesVisible = 0 console.log('gradus3') const artist = wand.artist const conductor = wand.conductor const net = wand.net const transfer = wand.transfer const names = $('').prop('title', 'show names') const input = $('').prop('title', 'load or upload network') names.prependTo('body') input.prependTo('body') const s = $('').appendTo('body') // window.qwe = $('
').appendTo('body') // // const s = $('', { id: 'file-select' }) .prop('atitle', 'select network').prependTo('body') if (!wand.sageInfo) { // load one of the networks this.allNetworks.forEach((n, i) => { s.append($('